<?php
    header('Content-Type: application/json');
    $response = ['success' => false, 'services' => [], 'pagination' => null, 'message' => 'Gagal memuat data 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 get_admin_services.php");
        $response['message'] = 'Koneksi database gagal.';
        echo json_encode($response);
        exit;
    }

    try {
        $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 15, 'min_range' => 5, 'max_range' => 250]]);
        $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
        $status = $_GET['status'] ?? 'all';
        $categoryId = $_GET['category_id'] ?? 'all';
        $providerId = $_GET['provider_id'] ?? 'all';
        $sortBy = $_GET['sort_by'] ?? 's.name';
        $sortType = $_GET['sort_type'] ?? 'ASC';
        $searchColumn = $_GET['search_column'] ?? 's.name';
        $searchKeyword = filter_input(INPUT_GET, 'search_keyword', FILTER_SANITIZE_SPECIAL_CHARS) ?? '';

        $offset = ($page - 1) * $limit;

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

        $allowedSearchColumns = ['s.id', 's.provider_service_id', 's.name', 'c.name', 'p.name'];
        if (!in_array($searchColumn, $allowedSearchColumns)) { $searchColumn = 's.name'; }

        $sqlSelect = "SELECT s.id, s.category_id, s.provider_id, s.provider_service_id, s.name, s.note, s.price_per_1000, s.min_order, s.max_order, s.status, s.created_at, s.updated_at, c.name as category_name, p.name as provider_name ";
        $sqlFrom = "FROM services s JOIN categories c ON s.category_id = c.id JOIN providers p ON s.provider_id = p.id ";
        $sqlWhereBase = "WHERE 1=1 ";
        $params = [];
        $whereClauses = [];

        if ($status !== 'all') {
            $validStatuses = ['active', 'inactive'];
            if (in_array($status, $validStatuses)) {
                $whereClauses[] = "s.status = :status";
                $params[':status'] = $status;
            }
        }
        if ($categoryId !== 'all' && filter_var($categoryId, FILTER_VALIDATE_INT)) {
            $whereClauses[] = "s.category_id = :category_id";
            $params[':category_id'] = (int)$categoryId;
        }
         if ($providerId !== 'all' && filter_var($providerId, FILTER_VALIDATE_INT)) {
            $whereClauses[] = "s.provider_id = :provider_id";
            $params[':provider_id'] = (int)$providerId;
        }

        if (!empty($searchKeyword)) {
            if ($searchColumn === 's.id' || $searchColumn === 's.provider_service_id') {
                 $whereClauses[] = $searchColumn . " = :search_keyword_id";
                 $params[':search_keyword_id'] = $searchKeyword; // ID bisa string atau angka
            } else {
                $whereClauses[] = $searchColumn . " LIKE :search_keyword";
                $params[':search_keyword'] = '%' . $searchKeyword . '%';
            }
        }

        $sqlWhere = $sqlWhereBase . (!empty($whereClauses) ? " AND " . implode(" AND ", $whereClauses) : "");

        $totalItems = 0;
        $totalPages = 1;
        $sqlCount = "SELECT COUNT(s.id) " . $sqlFrom . $sqlWhere;
        try {
            $stmtCount = $pdo->prepare($sqlCount);
            $stmtCount->execute($params);
            $totalItems = (int)$stmtCount->fetchColumn();
            $totalPages = $totalItems > 0 ? ceil($totalItems / $limit) : 1;
            if ($page > $totalPages) { $page = $totalPages; $offset = ($page - 1) * $limit; }
            elseif ($page < 1) { $page = 1; $offset = 0; }
        } catch (\PDOException $e) {
            error_log("Error counting admin services: " . $e->getMessage());
            throw $e;
        }

        $services = [];
        $sqlData = $sqlSelect . $sqlFrom . $sqlWhere . " ORDER BY {$sortBy} {$sortType} LIMIT :limit OFFSET :offset";
        try {
            $stmtData = $pdo->prepare($sqlData);
            foreach ($params as $key => &$value) {
                 if ($key === ':category_id' || $key === ':provider_id') {
                     $stmtData->bindValue($key, $value, PDO::PARAM_INT);
                 } elseif ($key === ':search_keyword_id') {
                      $stmtData->bindValue($key, $value);
                 }
                 else {
                     $stmtData->bindValue($key, $value);
                 }
            }
            unset($value);

            $stmtData->bindParam(':limit', $limit, PDO::PARAM_INT);
            $stmtData->bindParam(':offset', $offset, PDO::PARAM_INT);

            $stmtData->execute();
            $services = $stmtData->fetchAll(PDO::FETCH_ASSOC);

            $response['success'] = true;
            $response['services'] = $services;
            $response['pagination'] = [
                'totalItems' => $totalItems,
                'totalPages' => $totalPages,
                'currentPage' => $page,
                'limit' => $limit,
                'offset' => $offset
            ];
            unset($response['message']);

        } catch (\PDOException $e) {
            error_log("Error fetching admin services data: " . $e->getMessage());
            $response['message'] = "Gagal mengambil data layanan.";
            http_response_code(500);
        }

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