<?php

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

$response = ['success' => false, 'details' => null, 'message' => 'Terjadi kesalahan server awal.'];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("Error in get_service_details.php: PDO object not available from index.php.");
    $response['message'] = 'Koneksi database tidak tersedia.';
    echo json_encode($response);
    exit;
}

$response = ['success' => false, 'details' => null, 'message' => 'Gagal memuat detail layanan.'];

$serviceId = filter_input(INPUT_GET, 'service_id', FILTER_VALIDATE_INT);
if (!$serviceId) {
    $response['message'] = "ID Layanan tidak valid atau tidak diberikan.";
    echo json_encode($response);
    exit;
}

try {
    $sql = "SELECT `note`, `price_per_1000`, `min_order`, `max_order` FROM `services` WHERE `id` = :service_id AND `status` = 'active' LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':service_id', $serviceId, PDO::PARAM_INT);
    $stmt->execute();
    $details = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($details) {
        $response['success'] = true;
        $details['price_formatted'] = 'Rp ' . number_format($details['price_per_1000'] ?? 0, 0, ',', '.');
        $details['min_order_fmt'] = number_format($details['min_order'] ?? 0);
        $details['max_order_fmt'] = number_format($details['max_order'] ?? 0);
        $response['details'] = $details;
        unset($response['message']);
    } else {
        $response['message'] = "Detail layanan tidak ditemukan atau tidak aktif.";
    }
} catch (\PDOException $e) {
    error_log("AJAX Get Service Details DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan saat query detail layanan.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_db'] = $e->getMessage(); }
    http_response_code(500);

} catch (\Throwable $e) {
    error_log("AJAX Get Service Details 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;
?>
