<?php
/**
 * User - View Ticket
 */
require_once __DIR__ . '/../config.php';
require_login();

$page_title = 'View Ticket';
$user_id = $_SESSION['user_id'];
$ticket_id = intval($_GET['id'] ?? 0);

// Get ticket
$ticket = null;
$replies = [];
try {
    $stmt = db()->prepare("SELECT * FROM support_tickets WHERE id = ? AND user_id = ?");
    $stmt->execute([$ticket_id, $user_id]);
    $ticket = $stmt->fetch();
    
    if ($ticket) {
        $stmt = db()->prepare("SELECT * FROM ticket_replies WHERE ticket_id = ? ORDER BY created_at ASC");
        $stmt->execute([$ticket_id]);
        $replies = $stmt->fetchAll();
    }
} catch (PDOException $e) {}

if (!$ticket) {
    redirect(BASE_URL . 'user/tickets.php', 'error', 'Ticket not found');
}

// Add reply
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $message = sanitize($_POST['message'] ?? '');
        if (!empty($message)) {
            try {
                $stmt = db()->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message, is_admin_reply, created_at) VALUES (?, ?, ?, 0, NOW())");
                $stmt->execute([$ticket_id, $user_id, $message]);
                
                // Update ticket status
                $stmt = db()->prepare("UPDATE support_tickets SET status = 'open', updated_at = NOW() WHERE id = ?");
                $stmt->execute([$ticket_id]);
                
                redirect(BASE_URL . 'user/ticket-view.php?id=' . $ticket_id, 'success', 'Reply added');
            } catch (PDOException $e) {}
        }
    }
}

$csrf_token = generate_csrf_token();

include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Ticket #<?php echo $ticket['ticket_number']; ?></h2>
    <a href="tickets.php" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-2"></i>Back
    </a>
</div>

<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white py-3 d-flex justify-content-between">
        <div>
            <h5 class="mb-1"><?php echo $ticket['subject']; ?></h5>
            <small class="text-muted">Created: <?php echo format_date($ticket['created_at']); ?></small>
        </div>
        <div>
            <span class="badge bg-<?php 
                echo $ticket['status'] === 'open' ? 'danger' : 
                    ($ticket['status'] === 'in_progress' ? 'warning' : 'success'); 
            ?> me-2"><?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?></span>
            <span class="badge bg-<?php 
                echo $ticket['priority'] === 'urgent' ? 'danger' : 
                    ($ticket['priority'] === 'high' ? 'warning' : 
                    ($ticket['priority'] === 'medium' ? 'info' : 'secondary')); 
            ?>"><?php echo ucfirst($ticket['priority']); ?></span>
        </div>
    </div>
    <div class="card-body">
        <p><?php echo nl2br($ticket['message']); ?></p>
    </div>
</div>

<!-- Replies -->
<?php foreach ($replies as $reply): ?>
<div class="card border-0 shadow-sm mb-3 <?php echo $reply['is_admin_reply'] ? 'border-start border-primary border-4' : ''; ?>">
    <div class="card-body">
        <div class="d-flex justify-content-between mb-2">
            <span class="fw-bold <?php echo $reply['is_admin_reply'] ? 'text-primary' : ''; ?>">
                <?php echo $reply['is_admin_reply'] ? '<i class="bi bi-headset me-2"></i>Support Team' : '<i class="bi bi-person me-2"></i>You'; ?>
            </span>
            <small class="text-muted"><?php echo format_date($reply['created_at']); ?></small>
        </div>
        <p class="mb-0"><?php echo nl2br($reply['message']); ?></p>
    </div>
</div>
<?php endforeach; ?>

<!-- Reply Form -->
<?php if ($ticket['status'] !== 'closed'): ?>
<div class="card border-0 shadow-sm mt-4">
    <div class="card-body">
        <h6 class="mb-3">Add Reply</h6>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            <div class="mb-3">
                <textarea name="message" class="form-control" rows="4" placeholder="Type your message..." required></textarea>
            </div>
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-send me-2"></i>Send Reply
            </button>
        </form>
    </div>
</div>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>
