<?php
session_start();
include "../../connect/db.php";
csrf_verify();

// Check if ticket_id is set
if (isset($_POST['ticket_id'])) {
    $ticket_id = mysqli_real_escape_string($mysqli, $_POST['ticket_id']);

    // Fetch ticket details
    $query = "SELECT * FROM support_tickets WHERE ticket_id = ?";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param('s', $ticket_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $ticket = $result->fetch_assoc();

    // Fetch messages for the ticket
    $query = "SELECT message, created_at, name FROM support_tickets WHERE ticket_id = ? ORDER BY created_at";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param('s', $ticket_id);
    $stmt->execute();
    $messages_result = $stmt->get_result();
    
    $messages = [];
    while ($row = $messages_result->fetch_assoc()) {
        $messages[] = $row;
    }

    // Return ticket details and messages as JSON
    echo json_encode([
        'ticket_id' => $ticket['ticket_id'],
        'message' => $ticket['message'],
        'messages' => $messages
    ]);
}
?>
