<?php
    header('Content-Type: application/json');
    $response = ['success' => false, 'tickets' => [], 'pagination' => null, 'message' => 'Gagal memuat data 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() || $_SESSION['user_role'] !== 'admin') {
        http_response_code(403);
        $response['message'] = 'Akses ditolak. Hanya admin.';
        echo json_encode($response);
        exit;
    }

    if (!isset($pdo) || !$pdo instanceof PDO) {
        http_response_code(500);
        error_log("PDO object not available in get_admin_tickets.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' => 100]]);
        $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
        $status = $_GET['status'] ?? 'all';
        $userId = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
        $unread = $_GET['unread'] ?? 'all';
        $sortBy = $_GET['sort_by'] ?? 't.updated_at';
        $sortType = $_GET['sort_type'] ?? 'DESC';
        $searchColumn = $_GET['search_column'] ?? 't.ticket_id';
        $searchKeyword = filter_input(INPUT_GET, 'search_keyword', FILTER_SANITIZE_SPECIAL_CHARS) ?? '';

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

        $allowedSortColumns = ['t.updated_at', 't.created_at', 't.ticket_id', 't.subject', 'u.username', 't.status'];
        $allowedSortTypes = ['ASC', 'DESC'];
        if (!in_array($sortBy, $allowedSortColumns)) { $sortBy = 't.updated_at'; }
        if (!in_array(strtoupper($sortType), $allowedSortTypes)) { $sortType = 'DESC'; }

        $allowedSearchColumns = ['t.ticket_id', 't.subject', 'u.username', 't.user_id'];
        if (!in_array($searchColumn, $allowedSearchColumns)) { $searchColumn = 't.ticket_id'; }

        $sqlSelect = "SELECT t.id, t.ticket_id, t.user_id, t.subject, t.status, t.updated_at, t.created_at, t.is_read_admin, u.username ";
        $sqlFrom = "FROM tickets t JOIN users u ON t.user_id = u.id ";
        $sqlWhereBase = "WHERE 1=1 ";
        $params = [];
        $whereClauses = [];

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

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

        if ($unread === 'admin') {
            $whereClauses[] = "t.is_read_admin = 0";
        }

        if (!empty($searchKeyword)) {
            if ($searchColumn === 't.ticket_id') {
                $whereClauses[] = "t.ticket_id LIKE :search_keyword";
                $params[':search_keyword'] = '%' . $searchKeyword . '%';
            } elseif ($searchColumn === 't.user_id') {
                 if (is_numeric($searchKeyword)) {
                    $whereClauses[] = "t.user_id = :search_keyword_id";
                    $params[':search_keyword_id'] = (int)$searchKeyword;
                } else {
                    $whereClauses[] = "1 = 0";
                }
            } 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(t.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 tickets: " . $e->getMessage());
            throw $e;
        }

        $tickets = [];
        $sqlData = $sqlSelect . $sqlFrom . $sqlWhere . " ORDER BY {$sortBy} {$sortType} LIMIT :limit OFFSET :offset";
        try {
            $stmtData = $pdo->prepare($sqlData);

            foreach ($params as $key => &$value) {
                 if ($key === ':user_id' || $key === ':search_keyword_id') {
                     $stmtData->bindValue($key, $value, PDO::PARAM_INT);
                 } else {
                     $stmtData->bindValue($key, $value);
                 }
            }
            unset($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' => $totalItems,
                'totalPages' => $totalPages,
                'currentPage' => $page,
                'limit' => $limit,
                'offset' => $offset
            ];
            unset($response['message']); 

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

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