<?php
require_once '../functions.php';
requireAdminAuth();

$admin = getCurrentAdmin();
$db = getDB();

// Update ticket status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_ticket'])) {
    $ticketId = intval($_POST['ticket_id']);
    $newStatus = $_POST['status'];
    
    $stmt = $db->prepare("UPDATE support_tickets SET status = ? WHERE id = ?");
    $stmt->bind_param('si', $newStatus, $ticketId);
    $stmt->execute();
}

// Add reply
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_reply'])) {
    $ticketId = intval($_POST['ticket_id']);
    $message = trim($_POST['reply_message'] ?? '');
    
    if (!empty($message)) {
        $stmt = $db->prepare("INSERT INTO ticket_replies (ticket_id, admin_id, message, is_admin_reply) VALUES (?, ?, ?, 1)");
        $stmt->bind_param('iis', $ticketId, $admin['id'], $message);
        $stmt->execute();
    }
}

$statusFilter = $_GET['status'] ?? '';
$tickets = getSupportTickets($statusFilter ?: null);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support Tickets - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <?php include 'includes/admin-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/admin-header.php'; ?>
        
        <div class="page-content">
            <!-- Status Tabs -->
            <div class="tabs">
                <a href="tickets.php" class="tab-btn <?php echo $statusFilter === '' ? 'active' : ''; ?>">All (<?php echo $db->query("SELECT COUNT(*) as c FROM support_tickets")->fetch_assoc()['c']; ?>)</a>
                <a href="?status=open" class="tab-btn <?php echo $statusFilter === 'open' ? 'active' : ''; ?>">Open (<?php echo $db->query("SELECT COUNT(*) as c FROM support_tickets WHERE status = 'open'")->fetch_assoc()['c']; ?>)</a>
                <a href="?status=assigned" class="tab-btn <?php echo $statusFilter === 'assigned' ? 'active' : ''; ?>">Assigned (<?php echo $db->query("SELECT COUNT(*) as c FROM support_tickets WHERE status = 'assigned'")->fetch_assoc()['c']; ?>)</a>
                <a href="?status=resolved" class="tab-btn <?php echo $statusFilter === 'resolved' ? 'active' : ''; ?>">Resolved (<?php echo $db->query("SELECT COUNT(*) as c FROM support_tickets WHERE status = 'resolved'")->fetch_assoc()['c']; ?>)</a>
                <a href="?status=closed" class="tab-btn <?php echo $statusFilter === 'closed' ? 'active' : ''; ?>">Closed (<?php echo $db->query("SELECT COUNT(*) as c FROM support_tickets WHERE status = 'closed'")->fetch_assoc()['c']; ?>)</a>
            </div>
            
            <div class="card">
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Ticket #</th>
                                    <th>User</th>
                                    <th>Subject</th>
                                    <th>Category</th>
                                    <th>Priority</th>
                                    <th>Status</th>
                                    <th>Created</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($tickets->num_rows > 0): ?>
                                    <?php while ($t = $tickets->fetch_assoc()): ?>
                                        <tr>
                                            <td><code style="font-size: 12px; color: var(--primary); font-weight: 700;"><?php echo e($t['ticket_number']); ?></code></td>
                                            <td>
                                                <div style="font-weight: 600; font-size: 13px;"><?php echo e($t['first_name'] . ' ' . $t['last_name']); ?></div>
                                                <div style="font-size: 11px; color: var(--gray);"><?php echo e($t['email']); ?></div>
                                            </td>
                                            <td><?php echo e($t['subject']); ?></td>
                                            <td><span style="text-transform: capitalize;"><?php echo e($t['category']); ?></span></td>
                                            <td>
                                                <span class="status-badge <?php echo $t['priority'] === 'critical' ? 'danger' : ($t['priority'] === 'high' ? 'warning' : ($t['priority'] === 'medium' ? 'info' : 'secondary')); ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($t['priority'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="status-badge <?php echo $t['status'] === 'open' ? 'info' : ($t['status'] === 'resolved' ? 'success' : ($t['status'] === 'closed' ? 'secondary' : 'warning')); ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($t['status'])); ?>
                                                </span>
                                            </td>
                                            <td style="font-size: 12px;"><?php echo formatDateShort($t['created_at']); ?></td>
                                            <td>
                                                <button class="btn btn-sm btn-outline-primary" onclick="openModal('modal-ticket-<?php echo $t['id']; ?>')">Reply</button>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="8" class="text-center" style="padding: 40px; color: var(--gray);">No tickets found</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php 
    $tickets->data_seek(0);
    while ($t = $tickets->fetch_assoc()): 
        // Get replies for this ticket
        $stmt = $db->prepare("SELECT r.*, a.full_name as admin_name FROM ticket_replies r LEFT JOIN admin_users a ON r.admin_id = a.id WHERE r.ticket_id = ? ORDER BY r.created_at ASC");
        $stmt->bind_param('i', $t['id']);
        $stmt->execute();
        $replies = $stmt->get_result();
    ?>
    <div class="modal-overlay" id="modal-ticket-<?php echo $t['id']; ?>">
        <div class="modal modal-lg">
            <div class="modal-header">
                <div>
                    <span class="modal-title"><?php echo e($t['subject']); ?></span>
                    <div style="font-size: 12px; color: var(--gray);"><?php echo e($t['ticket_number']); ?> • <?php echo e($t['first_name'] . ' ' . $t['last_name']); ?></div>
                </div>
                <button class="modal-close" onclick="closeModal('modal-ticket-<?php echo $t['id']; ?>')">✕</button>
            </div>
            <div class="modal-body">
                <!-- Original Message -->
                <div style="background: var(--gray-50); border-radius: var(--border-radius); padding: 16px; margin-bottom: 20px;">
                    <div style="font-size: 12px; color: var(--gray); margin-bottom: 8px;">Original Message</div>
                    <p style="margin: 0;"><?php echo nl2br(e($t['message'])); ?></p>
                </div>
                
                <!-- Replies -->
                <?php if ($replies->num_rows > 0): ?>
                    <div style="margin-bottom: 20px;">
                        <div style="font-size: 12px; font-weight: 700; text-transform: uppercase; color: var(--gray); margin-bottom: 12px;">Conversation</div>
                        <?php while ($r = $replies->fetch_assoc()): ?>
                            <div style="padding: 12px; border-radius: var(--border-radius); margin-bottom: 8px; <?php echo $r['is_admin_reply'] ? 'background: var(--primary-light); border-left: 3px solid var(--primary);' : 'background: var(--gray-100);'; ?>">
                                <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                                    <span style="font-weight: 700; font-size: 12px;"><?php echo $r['is_admin_reply'] ? '👤 ' . e($r['admin_name'] ?? 'Support') : '🙂 User'; ?></span>
                                    <span style="font-size: 11px; color: var(--gray);"><?php echo formatDateShort($r['created_at']); ?></span>
                                </div>
                                <p style="margin: 0; font-size: 13px;"><?php echo nl2br(e($r['message'])); ?></p>
                            </div>
                        <?php endwhile; ?>
                    </div>
                <?php endif; ?>
                
                <!-- Status Update -->
                <form method="POST" action="" style="margin-bottom: 16px;">
                    <input type="hidden" name="ticket_id" value="<?php echo $t['id']; ?>">
                    <input type="hidden" name="update_ticket" value="1">
                    <div style="display: flex; gap: 12px; align-items: end;">
                        <div class="form-group" style="margin-bottom: 0; flex: 1;">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">
                                <option value="open" <?php echo $t['status'] === 'open' ? 'selected' : ''; ?>>Open</option>
                                <option value="assigned" <?php echo $t['status'] === 'assigned' ? 'selected' : ''; ?>>Assigned</option>
                                <option value="resolved" <?php echo $t['status'] === 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                                <option value="closed" <?php echo $t['status'] === 'closed' ? 'selected' : ''; ?>>Closed</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary">Update</button>
                    </div>
                </form>
                
                <!-- Reply Form -->
                <form method="POST" action="">
                    <input type="hidden" name="ticket_id" value="<?php echo $t['id']; ?>">
                    <input type="hidden" name="add_reply" value="1">
                    <div class="form-group">
                        <label class="form-label">Reply</label>
                        <textarea name="reply_message" class="form-control" rows="3" required placeholder="Type your reply..."></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Send Reply</button>
                </form>
            </div>
        </div>
    </div>
    <?php endwhile; ?>
    
    <script src="../assets/js/main.js"></script>
</body>
</html>
