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

    require_once __DIR__ . '/../../../config/config.php';
    require_once __DIR__ . '/../../../includes/session.php';
    require_once __DIR__ . '/../../../lib/Auth.php';
    require_once __DIR__ . '/../../../includes/functions.php';
    require_once __DIR__ . '/../../../includes/db_connect.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_service.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);
    $serviceIdToDelete = filter_var($requestData['service_id'] ?? null, FILTER_VALIDATE_INT);

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

    try {
        // Optional: Check if there are active orders for this service before deleting
        // $stmtCheckOrders = $pdo->prepare("SELECT COUNT(id) FROM orders WHERE service_id = :sid AND status NOT IN ('success', 'error', 'canceled', 'partial')");
        // $stmtCheckOrders->bindParam(':sid', $serviceIdToDelete, PDO::PARAM_INT);
        // $stmtCheckOrders->execute();
        // $activeOrderCount = (int)$stmtCheckOrders->fetchColumn();
        // if ($activeOrderCount > 0) {
        //     http_response_code(400);
        //     $response['message'] = "Tidak dapat menghapus layanan karena masih ada {$activeOrderCount} pesanan aktif yang menggunakannya.";
        //     echo json_encode($response);
        //     exit;
        // }

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

        if ($stmt->execute()) {
            if ($stmt->rowCount() > 0) {
                $response['success'] = true;
                $response['message'] = "Layanan (ID: {$serviceIdToDelete}) berhasil dihapus.";
            } else {
                http_response_code(404);
                $response['message'] = 'Layanan tidak ditemukan.';
            }
        } else {
            http_response_code(500);
            $response['message'] = 'Gagal menghapus layanan dari database.';
            error_log("Failed to delete service ID {$serviceIdToDelete}: " . implode(", ", $stmt->errorInfo()));
        }
    } catch (\PDOException $e) {
        error_log("Admin Delete Service DB Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan database saat menghapus layanan.";
        // Check for foreign key constraint errors if orders table depends on it
        // if (isset($e->errorInfo[1]) && ($e->errorInfo[1] == 1451 || $e->errorInfo[1] == 1217)) {
        //     $response['message'] = "Tidak dapat menghapus layanan karena masih digunakan dalam pesanan.";
        //      http_response_code(400);
        // } else {
             http_response_code(500);
        // }
    } catch (\Throwable $e) {
        error_log("Admin Delete Service 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;
    ?>
    