<?php
header('Content-Type: application/json');
$response = ['success' => false, 'tickets' => [], 'pagination' => null, 'message' => 'Gagal memuat daftar tiket.'];

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 (!Auth::isLoggedIn()) { http_response_code(401); $response['message'] = 'Sesi berakhir.'; echo json_encode($response); exit; }
if (!isset($pdo) || !$pdo instanceof PDO) { http_response_code(500); error_log("PDO object not available in get_tickets_list.php"); $response['message'] = 'Koneksi database gagal.'; echo json_encode($response); exit; }

try {
    $userId = $_SESSION['user_id'];
    $isAdmin = ($_SESSION['user_role'] === 'admin'); 

    $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 15, 'min_range' => 5, 'max_range' => 100]]);
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
    $statusFilter = $_GET['status'] ?? 'all';
    $offset = ($page - 1) * $limit;

    $sqlBase = "FROM tickets t ";
    $whereClauses = [];
    $params = [];

    if (!$isAdmin) {
        $whereClauses[] = "t.user_id = :user_id";
        $params[':user_id'] = $userId;
    }

    if ($statusFilter !== 'all') {
        $validStatuses = ['open', 'answered', 'user_reply', 'closed'];
        if (in_array($statusFilter, $validStatuses)) {
            $whereClauses[] = "t.status = :status";
            $params[':status'] = $statusFilter;
        }
    }

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

    $sqlCount = "SELECT COUNT(t.id) " . $sqlBase . $sqlWhere;
    $stmtCount = $pdo->prepare($sqlCount);
    $stmtCount->execute($params);
    $totalTickets = (int)$stmtCount->fetchColumn();
    $totalPages = $totalTickets > 0 ? ceil($totalTickets / $limit) : 1;
    if ($page > $totalPages) { $page = $totalPages; $offset = ($page - 1) * $limit; }
    elseif ($page < 1) { $page = 1; $offset = 0; }

    $sqlData = "SELECT t.id, t.ticket_id, t.subject, t.status, t.updated_at " . $sqlBase . $sqlWhere . " ORDER BY t.updated_at DESC LIMIT :limit OFFSET :offset";
    $stmtData = $pdo->prepare($sqlData);

    foreach ($params as $key => $value) {
        $stmtData->bindValue($key, $value);
    }
    $stmtData->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmtData->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmtData->execute();
    $tickets = $stmtData->fetchAll(PDO::FETCH_ASSOC);

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

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