<?php

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

$response = ['success' => false, 'services' => [], '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_services_by_category.php: PDO object not available from index.php.");
    $response['message'] = 'Koneksi database tidak tersedia.';
    echo json_encode($response);
    exit;
}

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

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

try {
    $sql = "SELECT `id`, `name` FROM `services` WHERE `category_id` = :cat_id AND `status` = 'active' ORDER BY `name` ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':cat_id', $categoryId, PDO::PARAM_INT);
    $stmt->execute();
    $services = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $response['success'] = true;
    $response['services'] = $services;
    if (!empty($services)) {
        unset($response['message']); 
    } else {
        $response['message'] = 'Tidak ada layanan aktif untuk kategori ini.';
    }

} catch (\PDOException $e) {
    error_log("AJAX Get Services DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan saat query data layanan.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_db'] = $e->getMessage(); }
    http_response_code(500);

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