<?php
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => 'Gagal memperbarui 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/update_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 {
        $categoryId = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
        $name = sanitize_input($_POST['name'] ?? '');
        $iconClass = sanitize_input($_POST['icon_class'] ?? '');
        $status = sanitize_input($_POST['status'] ?? 'active');

        $errors = [];

        if (!$categoryId) {
            throw new InvalidArgumentException('ID kategori tidak valid.');
        }

        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 AND id != :id LIMIT 1");
            $stmtCheck->bindParam(':name', $name);
            $stmtCheck->bindParam(':id', $categoryId, PDO::PARAM_INT);
            $stmtCheck->execute();
            if ($stmtCheck->fetch()) {
                $errors['category_name'] = 'Nama kategori sudah digunakan oleh kategori lain.';
            }
        }

        if (!empty($errors)) {
            http_response_code(400);
            $response['message'] = 'Periksa kembali input Anda.';
            $response['errors'] = $errors;
        } else {
            $sql = "UPDATE categories SET
                        name = :name,
                        icon_class = :icon_class,
                        status = :status,
                        updated_at = NOW()
                    WHERE id = :id";

            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':name', $name);
            $iconParam = !empty($iconClass) ? $iconClass : null;
            $stmt->bindParam(':icon_class', $iconParam);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':id', $categoryId, PDO::PARAM_INT);

            if ($stmt->execute()) {
                if ($stmt->rowCount() > 0) {
                    $response['success'] = true;
                    $response['message'] = 'Kategori berhasil diperbarui.';
                } else {
                    $response['success'] = true; 
                    $response['message'] = 'Tidak ada perubahan data kategori.';
                }
            } else {
                http_response_code(500);
                $response['message'] = 'Gagal memperbarui kategori di database.';
                error_log("Failed to update category ID {$categoryId}: " . implode(", ", $stmt->errorInfo()));
            }
        }

    } catch (InvalidArgumentException $e) {
        http_response_code(400);
        $response['message'] = $e->getMessage();
    } catch (\PDOException $e) {
        error_log("Admin Update 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) {
             $response['message'] = "Nama kategori sudah digunakan oleh kategori lain.";
             $response['errors']['category_name'] = 'Nama kategori sudah digunakan oleh kategori lain.';
             http_response_code(400);
        } else {
             http_response_code(500);
        }
    } catch (\Throwable $e) {
        error_log("Admin Update 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;
    ?>
    