<?php

session_start();

require '../../config.php';
require '../functions.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_email'])){
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

$connect = connect($database);
if(!$connect){
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

$check_access = check_access($connect);

if ($check_access['user_role'] != 1 && $check_access['user_role'] != 2){
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

// Get category name from POST
$category_name = isset($_POST['category_name']) ? trim($_POST['category_name']) : '';

if (empty($category_name)) {
    echo json_encode(['success' => false, 'message' => 'Category name is required']);
    exit;
}

// Generate slug
$slug = strtolower($category_name);
$slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
$slug = trim($slug, '-');

// Check if category already exists
$check = $connect->prepare("SELECT blog_cat_id FROM blog_categories WHERE blog_cat_slug = ?");
$check->execute([$slug]);

if ($check->rowCount() > 0) {
    echo json_encode(['success' => false, 'message' => 'Category already exists']);
    exit;
}

try {
    // Insert new category
    $stmt = $connect->prepare("INSERT INTO blog_categories (blog_cat_name, blog_cat_slug, blog_cat_status) VALUES (?, ?, 1)");
    $stmt->execute([$category_name, $slug]);
    
    $category_id = $connect->lastInsertId();
    
    echo json_encode([
        'success' => true, 
        'category_id' => $category_id,
        'category_name' => $category_name,
        'category_slug' => $slug
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error creating category: ' . $e->getMessage()]);
}

?>
