<?php
require_once 'auth_guard.php';
$pageTitle = 'المستخدمون';
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id     = (int)($_POST['id'] ?? 0);
    if ($action === 'suspend')   { db()->prepare("UPDATE users SET status='suspended' WHERE id=?")->execute([$id]); $msg='تم تعليق الحساب.'; }
    if ($action === 'activate')  { db()->prepare("UPDATE users SET status='active' WHERE id=?")->execute([$id]); $msg='تم تفعيل الحساب ✅'; }
    if ($action === 'delete')    { db()->prepare("DELETE FROM users WHERE id=?")->execute([$id]); $msg='تم حذف المستخدم.'; }
}

$filter = $_GET['role'] ?? '';
$search = trim($_GET['q'] ?? '');
$where  = []; $params = [];
if ($filter) { $where[] = 'role=?'; $params[] = $filter; }
if ($search)  { $where[] = '(username LIKE ? OR email LIKE ?)'; $params[] = "%$search%"; $params[] = "%$search%"; }
$sql = "SELECT * FROM users" . ($where ? ' WHERE '.implode(' AND ',$where) : '') . " ORDER BY created_at DESC";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

include 'header.php';
?>

<div class="page-header">
  <div class="page-title">👥 المستخدمون</div>
  <div class="page-sub"><?= count($users) ?> مستخدم مسجل</div>
</div>

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

<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px;align-items:center">
  <form method="GET" style="display:flex;gap:8px;flex:1;min-width:200px">
    <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="🔍 بحث بالاسم أو البريد...">
    <?php if ($filter): ?><input type="hidden" name="role" value="<?= htmlspecialchars($filter) ?>"><?php endif; ?>
    <button type="submit" class="btn btn-primary btn-sm">بحث</button>
  </form>
  <div style="display:flex;gap:6px">
    <a href="users.php" class="btn btn-sm <?= !$filter?'btn-primary':'btn-ghost' ?>">الكل</a>
    <a href="?role=tourist" class="btn btn-sm <?= $filter==='tourist'?'btn-primary':'btn-ghost' ?>">سائح</a>
    <a href="?role=provider" class="btn btn-sm <?= $filter==='provider'?'btn-gold':'btn-ghost' ?>">مقدم خدمة</a>
  </div>
</div>

<div class="table-wrap">
  <div class="tbl-scroll">
    <table class="tbl">
      <thead><tr>
        <th>المستخدم</th><th>البريد</th><th>الدور</th><th>الحالة</th><th>تاريخ التسجيل</th><th>إجراءات</th>
      </tr></thead>
      <tbody>
      <?php foreach ($users as $u): ?>
        <tr>
          <td>
            <div style="display:flex;align-items:center;gap:8px">
              <div style="width:36px;height:36px;border-radius:50%;background:var(--gp);display:flex;align-items:center;justify-content:center;font-size:1rem;flex-shrink:0">
                <?= $u['role']==='provider'?'💼':'👤' ?>
              </div>
              <div style="font-weight:700"><?= htmlspecialchars($u['username']) ?></div>
            </div>
          </td>
          <td style="font-size:.82rem;color:var(--muted)"><?= htmlspecialchars($u['email']) ?></td>
          <td>
            <span class="badge <?= $u['role']==='provider'?'badge-gold':'badge-green' ?>">
              <?= $u['role']==='provider'?'💼 مقدم خدمة':'👤 سائح' ?>
            </span>
          </td>
          <td>
            <span class="badge <?= $u['status']==='active'?'badge-green':'badge-red' ?>">
              <?= $u['status']==='active'?'✅ نشط':'🔒 موقوف' ?>
            </span>
          </td>
          <td style="font-size:.78rem;color:var(--muted)"><?= date('d/m/Y', strtotime($u['created_at'])) ?></td>
          <td>
            <div style="display:flex;gap:5px">
              <?php if ($u['status']==='active'): ?>
                <form method="POST"><input type="hidden" name="action" value="suspend"><input type="hidden" name="id" value="<?= $u['id'] ?>">
                  <button type="submit" class="btn btn-danger btn-sm">🔒 تعليق</button>
                </form>
              <?php else: ?>
                <form method="POST"><input type="hidden" name="action" value="activate"><input type="hidden" name="id" value="<?= $u['id'] ?>">
                  <button type="submit" class="btn btn-primary btn-sm">🔓 تفعيل</button>
                </form>
              <?php endif; ?>
              <form method="POST" onsubmit="return confirm('حذف هذا المستخدم نهائياً؟')">
                <input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= $u['id'] ?>">
                <button type="submit" class="btn btn-danger btn-sm">🗑️</button>
              </form>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$users): ?>
        <tr><td colspan="6" style="text-align:center;color:var(--muted);padding:32px">لا يوجد مستخدمون.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

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