<?php
require_once 'functions.php';
requireAuth();

$user = getCurrentUser();
$db = getDB();

$ticketId = intval($_GET['id'] ?? 0);

// Get ticket
// --- Fetch Ticket ---
$stmt = $db->prepare("SELECT * FROM support_tickets WHERE id = ? AND user_id = ?");
$stmt->bind_param('ii', $ticketId, $user['id']);
$stmt->execute();
$ticket = $stmt->get_result()->fetch_assoc();

// 1. FREE THE RESULT HERE
$stmt->free_result(); 

if (!$ticket) {
    setFlash('Ticket not found.', 'error');
    header('Location: support.php');
    exit();
}

// Add reply
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply'])) {
    $message = trim($_POST['message'] ?? '');
    if (!empty($message)) {
        $stmt = $db->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message, is_admin_reply) VALUES (?, ?, ?, 0)");
        $stmt->bind_param('iis', $ticketId, $user['id'], $message);
        $stmt->execute();
        
        // Update ticket status
        $stmt = $db->prepare("UPDATE support_tickets SET status = 'open' WHERE id = ?");
        $stmt->bind_param('i', $ticketId);
        $stmt->execute();
        
        setFlash('Reply sent successfully.', 'success');
        header('Location: ticket.php?id=' . $ticketId);
        exit();
    }
}

// Get replies
// --- Fetch Replies ---
// 2. NOW IT IS SAFE TO PREPARE THE NEXT STATEMENT
$stmt = $db->prepare("
    SELECT r.*, 
           CONCAT(a.first_name, ' ', a.last_name) as admin_name, 
           a.username as admin_username 
    FROM ticket_replies r 
    LEFT JOIN admin_users a ON (r.sender_id = a.id AND r.sender_type = 'admin')
    WHERE r.ticket_id = ? 
    ORDER BY r.created_at ASC
");
$stmt->bind_param('i', $ticketId);
$stmt->execute();
$replies = $stmt->get_result();


$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ticket #<?php echo e($ticket['ticket_number']); ?> - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .ticket-message-bubble {
            padding: 16px 20px;
            border-radius: var(--border-radius);
            margin-bottom: 16px;
            max-width: 80%;
        }
        .ticket-message-bubble.user {
            background: var(--gray-100);
            margin-left: auto;
            border-bottom-right-radius: 4px;
        }
        .ticket-message-bubble.admin {
            background: var(--primary-light);
            border-bottom-left-radius: 4px;
            border-left: 3px solid var(--primary);
        }
        .ticket-message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 12px;
        }
        .ticket-message-author {
            font-weight: 700;
            color: var(--secondary);
        }
        .ticket-message-time {
            color: var(--gray);
        }
        .ticket-message-body {
            font-size: 14px;
            line-height: 1.6;
        }
    </style>
</head>
<body>
    <?php include 'includes/client-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/client-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <div style="margin-bottom: 24px;">
                <a href="support.php" style="color: var(--primary); font-weight: 600; font-size: 14px;">← Back to Support</a>
            </div>
            
            <!-- Ticket Details -->
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-header">
                    <div>
                        <span class="card-title"><?php echo e($ticket['subject']); ?></span>
                        <div style="font-size: 12px; color: var(--gray); margin-top: 4px;">
                            <?php echo e($ticket['ticket_number']); ?> • <?php echo ucfirst(e($ticket['category'])); ?> • <?php echo formatDate($ticket['created_at']); ?>
                        </div>
                    </div>
                    <span class="status-badge <?php 
                        echo $ticket['status'] === 'open' ? 'info' : 
                            ($ticket['status'] === 'resolved' ? 'success' : 
                            ($ticket['status'] === 'closed' ? 'secondary' : 'warning')); 
                    ?>"><?php echo ucfirst(e($ticket['status'])); ?></span>
                </div>
                <div class="card-body">
                    <div style="background: var(--gray-50); border-radius: var(--border-radius); padding: 20px;">
                        <p style="margin: 0; line-height: 1.7;"><?php echo nl2br(e($ticket['message'])); ?></p>
                    </div>
                </div>
            </div>
            
            <!-- Replies -->
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-header">
                    <span class="card-title">Conversation</span>
                </div>
                <div class="card-body">
                    <?php if ($replies->num_rows > 0): ?>
                        <?php while ($reply = $replies->fetch_assoc()): ?>
                            <div class="ticket-message-bubble <?php echo $reply['is_admin_reply'] ? 'admin' : 'user'; ?>">
                                <div class="ticket-message-header">
                                    <span class="ticket-message-author">
                                        <?php echo $reply['is_admin_reply'] ? '👤 ' . e($reply['admin_name'] ?? 'Support Agent') : '🙂 You'; ?>
                                    </span>
                                    <span class="ticket-message-time"><?php echo formatDate($reply['created_at']); ?></span>
                                </div>
                                <div class="ticket-message-body"><?php echo nl2br(e($reply['message'])); ?></div>
                            </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div style="text-align: center; padding: 40px; color: var(--gray);">
                            <p>No replies yet. Our support team will respond shortly.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Reply Form -->
            <?php if ($ticket['status'] !== 'closed'): ?>
            <div class="card">
                <div class="card-header">
                    <span class="card-title">Send Reply</span>
                </div>
                <div class="card-body">
                    <form method="POST" action="">
                        <input type="hidden" name="reply" value="1">
                        <div class="form-group">
                            <textarea name="message" class="form-control" rows="4" required placeholder="Type your message here..."></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">Send Reply</button>
                    </form>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <script src="assets/js/main.js"></script>
</body>
</html>
