<?php
require_once 'db.php';

try {
    $db = getDB1Connection();

    if (!isset($_GET['id'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Ticket ID is required'
        ]);
        exit();
    }

    $ticketId = $_GET['id'];
    
    $ticketQuery = $db->prepare("
        SELECT 
            t.*,
            u.username,
            u.email,
            u.role as user_role
        FROM support_tickets t
        JOIN utilisateurs u ON t.user_id = u.id
        WHERE t.id = ?
    ");
    
    $ticketQuery->execute([$ticketId]);
    $ticket = $ticketQuery->fetch(PDO::FETCH_ASSOC);

    if (!$ticket) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Ticket not found'
        ]);
        exit();
    }

    $responsesQuery = $db->prepare("
        SELECT 
            r.*,
            u.username,
            u.email,
            u.role as user_role
        FROM ticket_responses r
        JOIN utilisateurs u ON r.user_id = u.id
        WHERE r.ticket_id = ?
        ORDER BY r.created_at ASC
    ");
    
    $responsesQuery->execute([$ticketId]);
    $responses = $responsesQuery->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'ticket' => $ticket,
        'responses' => $responses
    ]);

} catch (PDOException $e) {
    error_log('Database Error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while retrieving ticket details'
    ]);
} catch (Exception $e) {
    error_log('General Error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'An unexpected error occurred'
    ]);
}