<?php
header('Content-Type: application/json');
$response = ['success' => false, 'ticket' => null, 'replies' => [], 'message' => 'Gagal memuat detail 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 (!defined('TICKET_UPLOAD_DIR')) {
    define('TICKET_UPLOAD_DIR', PUBLIC_ROOT . '/uploads/tickets/');
}


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_ticket_details.php"); $response['message'] = 'Koneksi database gagal.'; echo json_encode($response); exit; }

try {
    $userId = $_SESSION['user_id'];
    $isAdmin = ($_SESSION['user_role'] === 'admin');
    $ticketIdParam = sanitize_input($_GET['ticket_id'] ?? '');

    if (empty($ticketIdParam)) { throw new InvalidArgumentException("ID Tiket tidak valid."); }

    $sqlTicket = "SELECT t.id, t.ticket_id, t.user_id, t.subject, t.status, t.created_at, t.updated_at, t.is_read_user, t.is_read_admin
                  FROM tickets t
                  WHERE t.ticket_id = :ticket_id";

    if (!$isAdmin) { $sqlTicket .= " AND t.user_id = :user_id"; }
    $sqlTicket .= " LIMIT 1";

    $stmtTicket = $pdo->prepare($sqlTicket);
    $stmtTicket->bindParam(':ticket_id', $ticketIdParam);
    if (!$isAdmin) { $stmtTicket->bindParam(':user_id', $userId, PDO::PARAM_INT); }
    $stmtTicket->execute();
    $ticket = $stmtTicket->fetch(PDO::FETCH_ASSOC);

    if (!$ticket) { throw new InvalidArgumentException("Tiket tidak ditemukan atau Anda tidak punya akses."); }

    $sqlReplies = "SELECT tr.id, tr.user_id, tr.message, tr.attachment_filename, tr.created_at, u.username as sender_name, u.role as user_role
                   FROM ticket_replies tr
                   JOIN users u ON tr.user_id = u.id
                   WHERE tr.ticket_id = :internal_ticket_id
                   ORDER BY tr.created_at ASC";
    $stmtReplies = $pdo->prepare($sqlReplies);
    $stmtReplies->bindParam(':internal_ticket_id', $ticket['id'], PDO::PARAM_INT);
    $stmtReplies->execute();
    $replies = $stmtReplies->fetchAll(PDO::FETCH_ASSOC);

    foreach ($replies as &$reply) { 
        if (!empty($reply['attachment_filename'])) {
                 $reply['attachment_url'] = base_url('uploads/tickets/' . $reply['attachment_filename']);

        } else {
            $reply['attachment_url'] = null;
        }
    }
    unset($reply);

    $updateReadStatus = false;
    $sqlUpdateRead = "";
    if ($isAdmin && isset($ticket['is_read_admin']) && $ticket['is_read_admin'] == 0) {
        $sqlUpdateRead = "UPDATE tickets SET is_read_admin = 1 WHERE id = :internal_ticket_id";
        $updateReadStatus = true;
    } elseif (!$isAdmin && isset($ticket['is_read_user']) && $ticket['is_read_user'] == 0) {
        $sqlUpdateRead = "UPDATE tickets SET is_read_user = 1 WHERE id = :internal_ticket_id";
        $updateReadStatus = true;
    }

    if ($updateReadStatus && !empty($sqlUpdateRead)) {
        $stmtUpdateRead = $pdo->prepare($sqlUpdateRead);
        $stmtUpdateRead->bindParam(':internal_ticket_id', $ticket['id'], PDO::PARAM_INT);
        $stmtUpdateRead->execute();
    }


    $response['success'] = true;
    $response['ticket'] = $ticket;
    $response['replies'] = $replies; 
    $response['current_user_id'] = $userId;
    unset($response['message']);

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