<?php

header('Content-Type: application/json');
$response = ['success' => false, 'categories' => [], 'message' => 'Gagal memuat daftar 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';
if (!isset($pdo) || !$pdo instanceof PDO) { http_response_code(500); error_log("PDO object not available in get_services_list.php"); $response['message'] = 'Koneksi database gagal.'; echo json_encode($response); exit; }

try {
    $searchKeyword = filter_input(INPUT_GET, 'search_keyword', FILTER_SANITIZE_SPECIAL_CHARS) ?? '';
    $sortBy = $_GET['sort_by'] ?? 's.name'; 
    $sortType = $_GET['sort_type'] ?? 'ASC';

    $allowedSortColumns = ['s.name', 's.price_per_1000', 'c.name', 's.id'];
    $allowedSortTypes = ['ASC', 'DESC'];
    if (!in_array($sortBy, $allowedSortColumns)) { $sortBy = 's.name'; }
    if (!in_array(strtoupper($sortType), $allowedSortTypes)) { $sortType = 'ASC'; }

    $sql = "SELECT
                s.id, s.name as service_name, s.price_per_1000, s.min_order, s.max_order, s.note,
                c.id as category_id, c.name as category_name, c.icon_class as category_icon
            FROM services s
            JOIN categories c ON s.category_id = c.id
            WHERE s.status = 'active' AND c.status = 'active'";

    $params = [];
    $whereClauses = [];

    if (!empty($searchKeyword)) {
        $whereClauses[] = "(s.name LIKE :keyword OR s.id = :keyword_id)";
        $params[':keyword'] = '%' . $searchKeyword . '%';
        $params[':keyword_id'] = is_numeric($searchKeyword) ? (int)$searchKeyword : 0;
    }

    if (!empty($whereClauses)) {
        $sql .= " AND (" . implode(" AND ", $whereClauses) . ")";
    }

    $sql .= " ORDER BY c.name ASC, {$sortBy} {$sortType}";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $allServices = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $groupedServices = [];
    foreach ($allServices as $service) {
        $categoryId = $service['category_id'];
        if (!isset($groupedServices[$categoryId])) {
            $groupedServices[$categoryId] = [
                'id' => $categoryId,
                'name' => $service['category_name'],
                'icon_class' => $service['category_icon'],
                'services' => []
            ];
        }
        $groupedServices[$categoryId]['services'][] = [
            'id' => $service['id'],
            'name' => $service['service_name'],
            'price_per_1000' => $service['price_per_1000'],
            'min_order' => $service['min_order'],
            'max_order' => $service['max_order'],
            'note' => $service['note'] 
        ];
    }

    $response['success'] = true;
    $response['categories'] = array_values($groupedServices); 
    unset($response['message']);

} catch (\PDOException $e) {
    error_log("AJAX Get Services List DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database saat memuat layanan.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("AJAX Get Services List 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;
?>
