<?php
require_once 'auth_guard.php';
$pageTitle = 'الرسائل';
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id     = (int)($_POST['id'] ?? 0);
    if ($action === 'read')     { db()->prepare("UPDATE messages SET is_read=1 WHERE id=?")->execute([$id]); }
    if ($action === 'unread')   { db()->prepare("UPDATE messages SET is_read=0 WHERE id=?")->execute([$id]); }
    if ($action === 'delete')   { db()->prepare("DELETE FROM messages WHERE id=?")->execute([$id]); $msg='تم حذف الرسالة.'; }
    if ($action === 'read_all') { db()->query("UPDATE messages SET is_read=1"); $msg='تم تحديد جميع الرسائل كمقروءة.'; }
    header('Location: messages.php'); exit;
}

$filter = $_GET['filter'] ?? '';
$where  = []; $params = [];
if ($filter === 'unread') { $where[] = 'is_read=0'; }
if ($filter === 'read')   { $where[] = 'is_read=1'; }
$sql = "SELECT * FROM messages" . ($where ? ' WHERE '.implode(' AND ',$where) : '') . " ORDER BY created_at DESC";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$messages = $stmt->fetchAll();

include 'header.php';
?>

<div class="page-header" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
  <div>
    <div class="page-title">✉️ الرسائل</div>
    <div class="page-sub"><?= count($messages) ?> رسالة</div>
  </div>
  <form method="POST">
    <input type="hidden" name="action" value="read_all">
    <button type="submit" class="btn btn-ghost">✅ تحديد الكل كمقروءة</button>
  </form>
</div>

<?php if ($msg): ?><div class="ok-box"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

<div style="display:flex;gap:6px;margin-bottom:16px;flex-wrap:wrap">
  <a href="messages.php" class="btn btn-sm <?= !$filter?'btn-primary':'btn-ghost' ?>">الكل</a>
  <a href="?filter=unread" class="btn btn-sm <?= $filter==='unread'?'btn-gold':'btn-ghost' ?>">غير مقروءة</a>
  <a href="?filter=read"   class="btn btn-sm <?= $filter==='read'?'btn-primary':'btn-ghost' ?>">مقروءة</a>
</div>

<div style="display:flex;flex-direction:column;gap:12px">
<?php foreach ($messages as $m): ?>
  <div style="background:var(--white);border-radius:var(--rl);padding:18px;box-shadow:var(--sh);border-right:3px solid <?= $m['is_read']?'var(--border)':'var(--gold)' ?>">
    <div style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:10px">
      <div>
        <div style="font-weight:800;color:var(--dark)"><?= htmlspecialchars($m['name']) ?></div>
        <div style="font-size:.78rem;color:var(--muted)">
          ✉️ <?= htmlspecialchars($m['email']) ?>
          <?php if ($m['phone']): ?> · 📞 <?= htmlspecialchars($m['phone']) ?><?php endif; ?>
        </div>
        <div style="font-size:.72rem;color:var(--muted);margin-top:3px">
          🕒 <?= date('d/m/Y H:i', strtotime($m['created_at'])) ?>
          · 🌐 <?= strtoupper($m['lang']) ?>
          <?php if ($m['ip']): ?> · 🖥️ <?= htmlspecialchars($m['ip']) ?><?php endif; ?>
        </div>
      </div>
      <div style="display:flex;gap:6px;align-items:center">
        <span class="badge <?= $m['is_read']?'badge-green':'badge-gold' ?>"><?= $m['is_read']?'مقروءة':'جديدة' ?></span>
        <form method="POST" style="display:inline">
          <input type="hidden" name="action" value="<?= $m['is_read']?'unread':'read' ?>">
          <input type="hidden" name="id" value="<?= $m['id'] ?>">
          <button type="submit" class="btn btn-ghost btn-sm"><?= $m['is_read']?'تحديد كجديدة':'تحديد كمقروءة' ?></button>
        </form>
        <form method="POST" onsubmit="return confirm('حذف هذه الرسالة؟')">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" value="<?= $m['id'] ?>">
          <button type="submit" class="btn btn-danger btn-sm">🗑️</button>
        </form>
      </div>
    </div>
    <div style="font-size:.9rem;color:var(--text);line-height:1.6;background:var(--cream);border-radius:var(--r);padding:12px">
      <?= nl2br(htmlspecialchars($m['message'])) ?>
    </div>
  </div>
<?php endforeach; ?>
<?php if (!$messages): ?>
  <div style="text-align:center;color:var(--muted);padding:48px;background:var(--white);border-radius:var(--rl)">
    لا توجد رسائل <?= $filter==='unread'?'غير مقروءة' : '' ?>.
  </div>
<?php endif; ?>
</div>

<?php include 'footer.php'; ?>
