<?php
session_start();
include 'includes/header.php';
include 'includes/sidebar.php';

require '../includes/db.php';

// 🔐 ADMIN PROTECTION
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

// ===============================
// 🗑 DELETE TICKET
// ===============================
if (isset($_GET['delete'])) {

    $id = intval($_GET['delete']);

    mysqli_query($conn, "DELETE FROM support_tickets WHERE id='$id'");

   
}

// ===============================
// 📥 FETCH TICKETS
// ===============================
$tickets = mysqli_query($conn, "
    SELECT st.*, u.customer_id 
    FROM support_tickets st
    LEFT JOIN users u ON st.user_id = u.id
    ORDER BY st.id DESC
");
?>

<div style="max-width:1000px; margin:40px auto;">

    <h2>📩 Support Tickets</h2>

    <table width="100%" cellpadding="10" style="background:#1e293b; border-radius:10px;">

        <tr style="background:#111827;">
            <th>ID</th>
            <th>Customer ID</th>
            <th>Reference</th>
            <th>Email</th>
            <th>Message</th>
            <th>Date</th>
            <th>Action</th>
        </tr>

        <?php while($row = mysqli_fetch_assoc($tickets)): ?>

        <tr style="border-bottom:1px solid #374151;">
            <td><?php echo $row['id']; ?></td>
            <td><?php echo htmlspecialchars($row['customer_id']); ?></td>
            <td><?php echo htmlspecialchars($row['reference_code']); ?></td>
            <td><?php echo htmlspecialchars($row['email']); ?></td>

            <td style="max-width:250px;">
                <?php echo nl2br(htmlspecialchars($row['message'])); ?>
            </td>

            <td><?php echo $row['created_at']; ?></td>

            <td>
                <a href="?delete=<?php echo $row['id']; ?>" 
                   onclick="return confirm('Delete this ticket?')"
                   style="color:#ef4444; text-decoration:none;">
                    Delete
                </a>
            </td>
        </tr>

        <?php endwhile; ?>

    </table>

</div>
