<?php
require_once __DIR__ . '/../config/db.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['admin_id'])) { header('Location: /WATCHING/admin/login.php'); exit; }

// Create contacts table if it doesn't exist
$createTable = "CREATE TABLE IF NOT EXISTS contacts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    phone VARCHAR(20) NOT NULL,
    email VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
db()->query($createTable);

$contacts = db()->query("SELECT * FROM contacts ORDER BY created_at DESC");
?>
<!doctype html>
<html><head><link href="/WATCHING/assets/css/styles.css" rel="stylesheet"></head><body class="glass-bg">
<div class="container glass-card" style="padding:16px;margin-top:20px;">
  <h2>Contact Messages</h2>
  <table class="table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Phone</th>
        <th>Email</th>
        <th>Message</th>
        <th>Date</th>
      </tr>
    </thead>
    <tbody>
      <?php while ($contact = $contacts->fetch_assoc()): ?>
        <tr>
          <td><?php echo htmlspecialchars($contact['name']); ?></td>
          <td><?php echo htmlspecialchars($contact['phone']); ?></td>
          <td><?php echo htmlspecialchars($contact['email']); ?></td>
          <td style="max-width: 300px; word-wrap: break-word;">
            <?php echo nl2br(htmlspecialchars(substr($contact['message'], 0, 100))); ?>
            <?php if (strlen($contact['message']) > 100): ?>...<?php endif; ?>
          </td>
          <td><?php echo date('M j, Y g:i A', strtotime($contact['created_at'])); ?></td>
        </tr>
      <?php endwhile; ?>
    </tbody>
  </table>
  
  <?php if ($contacts->num_rows === 0): ?>
    <div class="alert">No contact messages yet.</div>
  <?php endif; ?>
  
  <div style="margin-top: 16px;">
    <a href="/WATCHING/admin/dashboard.php" class="btn">Back to Dashboard</a>
  </div>
</div>
</body></html>