<?php
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => 'Gagal menambahkan kategori.', 'errors' => []];

    require_once __DIR__ . '/../../../config/config.php';
    require_once __DIR__ . '/../../../includes/session.php';
    require_once __DIR__ . '/../../../lib/Auth.php';
    require_once __DIR__ . '/../../../includes/functions.php';

    if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
        http_response_code(403);
        $response['message'] = 'Akses ditolak.';
        echo json_encode($response);
        exit;
    }

    if (!isset($pdo) || !$pdo instanceof PDO) {
        http_response_code(500);
        error_log("PDO object not available in admin/add_category.php");
        $response['message'] = 'Koneksi database gagal.';
        echo json_encode($response);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        $response['message'] = 'Metode request tidak valid.';
        echo json_encode($response);
        exit;
    }

    try {
        $name = sanitize_input($_POST['name'] ?? '');
        $iconClass = sanitize_input($_POST['icon_class'] ?? '');
        $status = sanitize_input($_POST['status'] ?? 'active');

        $errors = [];

        if (empty($name)) {
            $errors['category_name'] = 'Nama kategori wajib diisi.';
        } elseif (mb_strlen($name) > 100) { 
            $errors['category_name'] = 'Nama kategori terlalu panjang (maks 100 karakter).';
        }

        if (!empty($iconClass) && !preg_match('/^(fas|fab|far)\sfa-[a-z0-9\-]+$/i', $iconClass)) {
             $errors['category_icon_class'] = 'Format kelas ikon tidak valid (contoh: fas fa-star).';
        }

        if (!in_array($status, ['active', 'inactive'])) {
            $errors['category_status'] = 'Status tidak valid.';
        }

        if (empty($errors)) {
            $stmtCheck = $pdo->prepare("SELECT id FROM categories WHERE name = :name LIMIT 1");
            $stmtCheck->bindParam(':name', $name);
            $stmtCheck->execute();
            if ($stmtCheck->fetch()) {
                $errors['category_name'] = 'Nama kategori sudah ada.';
            }
        }

        if (!empty($errors)) {
            http_response_code(400);
            $response['message'] = 'Periksa kembali input Anda.';
            $response['errors'] = $errors;
        } else {
            $sql = "INSERT INTO categories (name, icon_class, status, created_at, updated_at)
                    VALUES (:name, :icon_class, :status, NOW(), NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':name', $name);
            $iconParam = !empty($iconClass) ? $iconClass : null;
            $stmt->bindParam(':icon_class', $iconParam);
            $stmt->bindParam(':status', $status);

            if ($stmt->execute()) {
                $response['success'] = true;
                $response['message'] = 'Kategori baru berhasil ditambahkan.';
            } else {
                http_response_code(500);
                $response['message'] = 'Gagal menambahkan kategori ke database.';
                 error_log("Failed to insert category: " . implode(", ", $stmt->errorInfo()));
            }
        }

    } catch (\PDOException $e) {
        error_log("Admin Add Category DB Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan database.";
        if (defined('DEBUG_MODE') && DEBUG_MODE === true && isset($e->errorInfo[1]) && $e->errorInfo[1] == 1062) { // Duplicate entry
             $response['message'] = "Nama kategori sudah ada.";
             $response['errors']['category_name'] = 'Nama kategori sudah ada.';
             http_response_code(400);
        } else {
             http_response_code(500);
        }
    } catch (\Throwable $e) {
        error_log("Admin Add Category General Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan internal server.";
        if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
        http_response_code(500);
    }

    echo json_encode($response);
    exit;
    ?>
    