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

    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/delete_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;
    }

    $requestData = json_decode(file_get_contents('php://input'), true);
    $categoryIdToDelete = filter_var($requestData['category_id'] ?? null, FILTER_VALIDATE_INT);

    if (!$categoryIdToDelete) {
        http_response_code(400);
        $response['message'] = 'ID kategori tidak valid.';
        echo json_encode($response);
        exit;
    }

    try {
        $pdo->beginTransaction();

        $stmtCheckServices = $pdo->prepare("SELECT COUNT(id) FROM services WHERE category_id = :category_id");
        $stmtCheckServices->bindParam(':category_id', $categoryIdToDelete, PDO::PARAM_INT);
        $stmtCheckServices->execute();
        $serviceCount = (int)$stmtCheckServices->fetchColumn();

        if ($serviceCount > 0) {
            $pdo->rollBack();
            http_response_code(400); 
            $response['message'] = "Tidak dapat menghapus kategori karena masih ada {$serviceCount} layanan terkait. Hapus atau pindahkan layanan terlebih dahulu.";
            echo json_encode($response);
            exit;
        }

        $sql = "DELETE FROM categories WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':id', $categoryIdToDelete, PDO::PARAM_INT);

        if ($stmt->execute()) {
            if ($stmt->rowCount() > 0) {
                $pdo->commit();
                $response['success'] = true;
                $response['message'] = "Kategori (ID: {$categoryIdToDelete}) berhasil dihapus.";
            } else {
                $pdo->rollBack(); 
                http_response_code(404);
                $response['message'] = 'Kategori tidak ditemukan.';
            }
        } else {
            $pdo->rollBack();
            http_response_code(500);
            $response['message'] = 'Gagal menghapus kategori dari database.';
            error_log("Failed to delete category ID {$categoryIdToDelete}: " . implode(", ", $stmt->errorInfo()));
        }
    } catch (\PDOException $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log("Admin Delete Category DB Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan database saat menghapus kategori.";
        http_response_code(500);
    } catch (\Throwable $e) {
         if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        error_log("Admin Delete 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;
    ?>
    