<?php
session_start();
require_once '../config.php';
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}
global $pdo;

$message = '';
if (isset($_GET['close'])) {
    $id = (int)$_GET['close'];
    $pdo->prepare("UPDATE support_tickets SET status = 'closed' WHERE id = ?")->execute([$id]);
    $message = '<div class="alert alert-warning fw-bold">Ticket closed.</div>';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_submit'])) {
    $tid = (int)$_POST['ticket_id'];
    $msg = trim($_POST['reply_msg'] ?? '');
    if ($msg !== '') {
        $pdo->prepare("INSERT INTO support_messages (ticket_id, is_admin, message) VALUES (?, 1, ?)")->execute([$tid, $msg]);
        $message = '<div class="alert alert-success fw-bold">Reply sent.</div>';
    }
}

$tickets = $pdo->query("
    SELECT t.*, u.username, u.mobile
    FROM support_tickets t
    LEFT JOIN users u ON u.id = t.user_id
    ORDER BY t.id DESC
    LIMIT 100
")->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Support Chat';
require_once 'includes/header.php';
?>
<?= $message ?>
<div class="custom-card">
    <div class="custom-card-header"><i class="fas fa-headset me-2"></i> Support Tickets</div>
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th>ID</th>
                    <th>User</th>
                    <th>Type</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th class="text-end">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($tickets)): ?>
                    <tr><td colspan="6" class="text-center py-4 text-muted">No tickets yet.</td></tr>
                <?php else: foreach ($tickets as $t): ?>
                    <tr>
                        <td>#<?= $t['id'] ?></td>
                        <td><?= htmlspecialchars($t['username'] ?? '-') ?><br><small><?= htmlspecialchars($t['mobile'] ?? '') ?></small></td>
                        <td><span class="badge bg-secondary"><?= htmlspecialchars($t['problem_type']) ?></span></td>
                        <td><?= $t['status'] === 'open' ? '<span class="badge bg-success">Open</span>' : '<span class="badge bg-secondary">Closed</span>' ?></td>
                        <td><small><?= $t['created_at'] ?></small></td>
                        <td class="text-end">
                            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#replyModal" data-id="<?= $t['id'] ?>" data-user="<?= htmlspecialchars($t['username'] ?? '') ?>">Reply</button>
                            <?php if ($t['status'] === 'open'): ?>
                                <a href="?close=<?= $t['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Close this ticket?');">Close</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="replyModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Reply to <span id="modalUser"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="ticket_id" id="modalTicketId">
                    <label class="form-label fw-bold">Message</label>
                    <textarea name="reply_msg" class="form-control" rows="3" required placeholder="Type your reply..."></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="reply_submit" class="btn btn-primary fw-bold">Send Reply</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
document.getElementById('replyModal').addEventListener('show.bs.modal', function(e) {
    const btn = e.relatedTarget;
    document.getElementById('modalTicketId').value = btn.getAttribute('data-id');
    document.getElementById('modalUser').textContent = btn.getAttribute('data-user') || '';
});
</script>
<?php require_once 'includes/footer.php'; ?>
