<?php
/**
 * Admin - View & Reply to Ticket
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

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

// Get ticket
$ticket = null;
$replies = [];
$user = null;
try {
    $stmt = db()->prepare("SELECT t.*, u.full_name, u.email FROM support_tickets t JOIN users u ON t.user_id = u.id WHERE t.id = ?");
    $stmt->execute([$ticket_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 . 'admin/tickets.php', 'error', 'Ticket not found');
}

// Add admin reply
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $message = sanitize($_POST['message'] ?? '');
        $new_status = $_POST['status'] ?? $ticket['status'];
        
        if (!empty($message)) {
            try {
                $stmt = db()->prepare("INSERT INTO ticket_replies (ticket_id, user_id, message, is_admin_reply, created_at) VALUES (?, ?, ?, 1, NOW())");
                $stmt->execute([$ticket_id, $_SESSION['admin_id'], $message]);
                
                // Update ticket status
                $stmt = db()->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$new_status, $ticket_id]);
                
                redirect(BASE_URL . 'admin/ticket-view.php?id=' . $ticket_id, 'success', 'Reply sent');
            } 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 to Tickets
    </a>
</div>

<div class="row">
    <div class="col-lg-8">
        <!-- Ticket Details -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white py-3">
                <div class="d-flex justify-content-between">
                    <div>
                        <h5 class="mb-1"><?php echo $ticket['subject']; ?></h5>
                        <small class="text-muted">From: <?php echo $ticket['full_name']; ?> (<?php echo $ticket['email']; ?>)</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>
                    </div>
                </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' : 'border-start border-success 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' : 'text-success'; ?>">
                        <?php echo $reply['is_admin_reply'] ? '<i class="bi bi-headset me-2"></i>Support Team' : '<i class="bi bi-person me-2"></i>' . $ticket['full_name']; ?>
                    </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 -->
        <div class="card border-0 shadow-sm mt-4">
            <div class="card-body">
                <h6 class="mb-3">Reply to Ticket</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 reply..." required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Update Status</label>
                        <select name="status" class="form-select">
                            <option value="in_progress" <?php echo $ticket['status'] === 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                            <option value="resolved" <?php echo $ticket['status'] === 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                            <option value="closed" <?php echo $ticket['status'] === 'closed' ? 'selected' : ''; ?>>Closed</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-send me-2"></i>Send Reply
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h6 class="mb-0">Ticket Info</h6>
            </div>
            <div class="card-body">
                <p class="mb-2"><strong>Ticket #:</strong> <?php echo $ticket['ticket_number']; ?></p>
                <p class="mb-2"><strong>Priority:</strong> <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></p>
                <p class="mb-2"><strong>Created:</strong> <?php echo format_date($ticket['created_at']); ?></p>
                <p class="mb-0"><strong>Last Updated:</strong> <?php echo format_date($ticket['updated_at']); ?></p>
            </div>
        </div>
    </div>
</div>

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