<?php
$active = 'contact';
$pageTitle = 'Contact Enquiries';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$messages = $pdo->query("SELECT * FROM contact_messages ORDER BY created_at DESC LIMIT 200")->fetchAll(PDO::FETCH_ASSOC);
$totalCount = (int)$pdo->query("SELECT COUNT(*) FROM contact_messages")->fetchColumn();
?>
<div class="page-header">
  <h1>Contact Enquiries</h1>
  <p class="subtitle">Messages from the website contact form (<?php echo $totalCount; ?> total)</p>
</div>

<div class="card">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Message</th>
            <th>Date</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($messages as $m): ?>
          <tr>
            <td>#<?php echo $m['id']; ?></td>
            <td><?php echo htmlspecialchars($m['name']); ?></td>
            <td><a href="mailto:<?php echo htmlspecialchars($m['email']); ?>"><?php echo htmlspecialchars($m['email']); ?></a></td>
            <td><?php echo htmlspecialchars($m['phone'] ?? '-'); ?></td>
            <td style="max-width: 300px;" class="small">
              <?php $msg = $m['message']; $short = strlen($msg) > 120 ? substr($msg, 0, 120) . '...' : $msg; ?>
              <span class="msg-preview"><?php echo htmlspecialchars($short); ?></span>
              <button type="button" class="btn btn-link btn-sm p-0 ms-1" data-bs-toggle="modal" data-bs-target="#msgModal<?php echo $m['id']; ?>">View</button>
              <div class="modal fade" id="msgModal<?php echo $m['id']; ?>" tabindex="-1">
                <div class="modal-dialog">
                  <div class="modal-content">
                    <div class="modal-header"><h5 class="modal-title">Message #<?php echo $m['id']; ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                    <div class="modal-body"><pre class="mb-0" style="white-space: pre-wrap;"><?php echo htmlspecialchars($msg); ?></pre></div>
                  </div>
                </div>
              </div>
            </td>
            <td class="small"><?php echo date('M d, Y H:i', strtotime($m['created_at'])); ?></td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($messages)): ?>
          <tr><td colspan="6" class="text-muted text-center py-4">No contact messages yet.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
