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

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if ($action === 'approve') {
        db()->prepare("UPDATE providers SET status='approved' WHERE id=?")->execute([$id]);
        $msg = 'تمت الموافقة على النشاط ✅';
    }
    if ($action === 'reject') {
        db()->prepare("UPDATE providers SET status='rejected' WHERE id=?")->execute([$id]);
        $msg = 'تم رفض النشاط.';
    }
    if ($action === 'delete') {
        db()->prepare("DELETE FROM providers WHERE id=?")->execute([$id]);
        db()->prepare("DELETE FROM users WHERE id=(SELECT user_id FROM providers WHERE id=?) AND role='provider'")->execute([$id]);
        $msg = 'تم حذف النشاط والحساب المرتبط به.';
    }
    if ($action === 'suspend_user') {
        $uid = (int)$_POST['user_id'];
        db()->prepare("UPDATE users SET status='suspended' WHERE id=?")->execute([$uid]);
        $msg = 'تم تعليق حساب المستخدم.';
    }
}

$filter = $_GET['filter'] ?? '';
$search = trim($_GET['q'] ?? '');

$where  = [];
$params = [];
if ($filter) { $where[] = 'p.status = ?'; $params[] = $filter; }
if ($search)  { $where[] = '(p.business_name LIKE ? OR u.username LIKE ?)'; $params[] = "%$search%"; $params[] = "%$search%"; }

$sql = "SELECT p.*, u.username, u.status as user_status FROM providers p
        JOIN users u ON u.id = p.user_id"
     . ($where ? ' WHERE ' . implode(' AND ', $where) : '')
     . " ORDER BY FIELD(p.status,'pending','approved','rejected'), p.created_at DESC";

$stmt = db()->prepare($sql);
$stmt->execute($params);
$providers = $stmt->fetchAll();

$act_icons  = ['restaurant'=>'🍽️','hotel'=>'🏨','guide'=>'🗺️','craft'=>'🛍️','agency'=>'✈️','transport'=>'🚲'];
$act_labels = ['restaurant'=>'مطعم/مقهى','hotel'=>'فندق/إقامة','guide'=>'مرشد سياحي','craft'=>'صناعة تقليدية','agency'=>'وكالة سياحية','transport'=>'توصيل/نقل'];

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($providers) ?> نشاط</div>
  </div>
</div>

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

<!-- Filters -->
<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="filter" value="<?= htmlspecialchars($filter) ?>"><?php endif; ?>
    <button type="submit" class="btn btn-primary btn-sm">بحث</button>
  </form>
  <div style="display:flex;gap:6px;flex-wrap:wrap">
    <a href="activities.php" class="btn btn-sm <?= !$filter ? 'btn-primary':'btn-ghost' ?>">الكل</a>
    <a href="?filter=pending" class="btn btn-sm <?= $filter==='pending'?'btn-gold':'btn-ghost' ?>">⏳ بانتظار الموافقة</a>
    <a href="?filter=approved" class="btn btn-sm <?= $filter==='approved'?'btn-primary':'btn-ghost' ?>">✅ مقبول</a>
    <a href="?filter=rejected" class="btn btn-sm <?= $filter==='rejected'?'btn-danger':'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 ($providers as $p): ?>
        <tr>
          <td>
            <div style="display:flex;align-items:center;gap:10px">
              <?php if ($p['image']): ?>
                <img src="../<?= htmlspecialchars($p['image']) ?>" style="width:48px;height:44px;object-fit:cover;border-radius:8px;flex-shrink:0">
              <?php else: ?>
                <div class="thumb"><?= $act_icons[$p['activity_type']] ?? '🏪' ?></div>
              <?php endif; ?>
              <div>
                <div style="font-weight:700"><?= htmlspecialchars($p['business_name']) ?></div>
                <div style="font-size:.75rem;color:var(--muted)">@<?= htmlspecialchars($p['username']) ?></div>
                <?php if ($p['description']): ?>
                  <div style="font-size:.72rem;color:var(--muted);max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= htmlspecialchars(mb_substr($p['description'],0,60)) ?></div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td>
            <span class="badge badge-green">
              <?= $act_icons[$p['activity_type']] ?? '' ?> <?= htmlspecialchars($act_labels[$p['activity_type']] ?? $p['activity_type']) ?>
            </span>
          </td>
          <td>
            <div style="font-size:.82rem">📞 <?= htmlspecialchars($p['phone']) ?></div>
            <div style="font-size:.78rem;color:var(--muted)">✉️ <?= htmlspecialchars($p['email']) ?></div>
            <?php if ($p['address']): ?>
              <div style="font-size:.72rem;color:var(--muted)">📍 <?= htmlspecialchars(mb_substr($p['address'],0,40)) ?></div>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($p['status'] === 'pending'): ?>
              <span class="badge badge-gold">⏳ بانتظار الموافقة</span>
            <?php elseif ($p['status'] === 'approved'): ?>
              <span class="badge badge-green">✅ مقبول</span>
            <?php else: ?>
              <span class="badge badge-red">❌ مرفوض</span>
            <?php endif; ?>
            <?php if ($p['user_status'] === 'suspended'): ?>
              <br><span class="badge badge-gray" style="margin-top:4px">🔒 حساب موقوف</span>
            <?php endif; ?>
          </td>
          <td style="font-size:.78rem;color:var(--muted)"><?= date('d/m/Y', strtotime($p['created_at'])) ?></td>
          <td>
            <div style="display:flex;gap:5px;flex-wrap:wrap">
              <?php if ($p['status'] === 'pending'): ?>
                <form method="POST" style="display:inline">
                  <input type="hidden" name="action" value="approve">
                  <input type="hidden" name="id" value="<?= $p['id'] ?>">
                  <button type="submit" class="btn btn-primary btn-sm">✅ قبول</button>
                </form>
                <form method="POST" style="display:inline">
                  <input type="hidden" name="action" value="reject">
                  <input type="hidden" name="id" value="<?= $p['id'] ?>">
                  <button type="submit" class="btn btn-danger btn-sm">❌ رفض</button>
                </form>
              <?php elseif ($p['status'] === 'approved'): ?>
                <form method="POST" style="display:inline">
                  <input type="hidden" name="action" value="reject">
                  <input type="hidden" name="id" value="<?= $p['id'] ?>">
                  <button type="submit" class="btn btn-ghost btn-sm">إلغاء الموافقة</button>
                </form>
              <?php else: ?>
                <form method="POST" style="display:inline">
                  <input type="hidden" name="action" value="approve">
                  <input type="hidden" name="id" value="<?= $p['id'] ?>">
                  <button type="submit" class="btn btn-primary btn-sm">✅ قبول</button>
                </form>
              <?php endif; ?>

              <?php if ($p['lat'] && $p['lng']): ?>
                <button class="btn btn-ghost btn-sm"
                  onclick="showMap(<?= $p['lat'] ?>,<?= $p['lng'] ?>,'<?= addslashes($p['business_name']) ?>')">🗺️</button>
              <?php endif; ?>

              <form method="POST" onsubmit="return confirm('حذف هذا النشاط نهائياً؟')">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $p['id'] ?>">
                <button type="submit" class="btn btn-danger btn-sm">🗑️</button>
              </form>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$providers): ?>
        <tr><td colspan="6" style="text-align:center;color:var(--muted);padding:32px">لا توجد أنشطة مسجلة.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Map modal -->
<div class="modal-overlay" id="mapModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title" id="mapModalTitle">موقع النشاط</div>
      <button class="modal-close">✕</button>
    </div>
    <div class="modal-body" style="padding:16px">
      <div id="providerMap" style="width:100%;height:280px;border-radius:var(--r)"></div>
    </div>
  </div>
</div>

<script>
var provMap = null;
function showMap(lat, lng, name) {
  document.getElementById('mapModalTitle').textContent = '📍 ' + name;
  document.getElementById('mapModal').classList.add('open');
  setTimeout(function() {
    if (!provMap) {
      provMap = L.map('providerMap').setView([lat,lng], 14);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution:'© OpenStreetMap'}).addTo(provMap);
    } else {
      provMap.setView([lat,lng], 14);
    }
    L.marker([lat,lng]).addTo(provMap).bindPopup('<strong>'+name+'</strong>').openPopup();
    provMap.invalidateSize();
  }, 150);
}
</script>

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