<?php $pageTitle = 'EL3AB - المنظمات'; ?>
<?php require __DIR__ . '/../includes/header.php'; ?>

<div class="space-y-6">

  <div class="text-center">
    <h2 style="font-size:22px;font-weight:700;">المنظمات</h2>
    <p class="text-muted text-sm">انضم لمنظمة او انشئ واحدة</p>
  </div>

  <!-- Tabs -->
  <div class="tab-group" id="orgs-tabs">
    <button class="tab active" data-tab="my">منظماتي</button>
    <button class="tab" data-tab="browse">تصفح</button>
  </div>

  <!-- My Orgs -->
  <div id="tab-my" class="space-y-3">
    <div id="my-orgs">
      <div class="card"><div class="empty-state">
        <svg class="icon-lg" style="color:var(--text-3);margin-bottom:8px;"><use href="/public/icons/sprite.svg#icon-org"></use></svg>
        <p>لم تنضم لأي منظمة</p>
      </div></div>
    </div>
  </div>

  <!-- Browse -->
  <div id="tab-browse" class="space-y-3" style="display:none;">
    <div class="input-group">
      <svg class="icon input-icon"><use href="/public/icons/sprite.svg#icon-search"></use></svg>
      <input type="text" class="input" id="org-search" placeholder="ابحث عن منظمة...">
    </div>
    <div id="browse-orgs">
      <div class="card"><div class="empty-state">جاري التحميل...</div></div>
    </div>
  </div>

  <!-- Create -->
  <button class="btn btn-cyan btn-block" onclick="showCreateOrg()">
    <svg class="icon"><use href="/public/icons/sprite.svg#icon-plus"></use></svg>
    انشاء منظمة
  </button>

</div>

<!-- Create Modal (hidden) -->
<div id="create-org-modal" style="display:none;position:fixed;inset:0;background:var(--overlay-dark);z-index:100;display:none;align-items:center;justify-content:center;padding:20px;">
  <div class="card" style="max-width:400px;width:100%;">
    <div class="card-body space-y-4" style="padding:24px;">
      <p style="font-size:18px;font-weight:700;text-align:center;">انشاء منظمة</p>
      <div>
        <label class="input-label">اسم المنظمة</label>
        <input type="text" class="input" id="org-name" placeholder="اسم المنظمة">
      </div>
      <div>
        <label class="input-label">الوصف</label>
        <input type="text" class="input" id="org-desc" placeholder="وصف قصير">
      </div>
      <div style="display:flex;gap:8px;">
        <button class="btn btn-gold" style="flex:1;" onclick="createOrg()">انشاء</button>
        <button class="btn btn-ghost" style="flex:1;" onclick="hideCreateOrg()">الغاء</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
  if (!App.isLoggedIn()) {
    window.location.href = '/login';
    return;
  }

  const tabs = document.querySelectorAll('#orgs-tabs .tab');
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      tabs.forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      document.getElementById('tab-my').style.display = tab.dataset.tab === 'my' ? 'block' : 'none';
      document.getElementById('tab-browse').style.display = tab.dataset.tab === 'browse' ? 'block' : 'none';
    });
  });

  loadOrgs();

  let searchTimeout;
  document.getElementById('org-search').addEventListener('input', (e) => {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => searchOrgs(e.target.value), 500);
  });
});

async function loadOrgs() {
  const data = await App.fetch('/api/orgs?action=my');
  if (data && data.orgs && data.orgs.length > 0) {
    document.getElementById('my-orgs').innerHTML = data.orgs.map(o => `
      <a href="/org?id=${o.id}" class="card card-hover" style="display:block;text-decoration:none;">
        <div class="card-body" style="display:flex;align-items:center;gap:16px;">
          <div class="avatar" style="background:var(--bg-3);">
            <svg class="icon-lg" style="color:var(--cyan)"><use href="/public/icons/sprite.svg#icon-org"></use></svg>
          </div>
          <div style="flex:1;">
            <p style="font-size:15px;font-weight:600;">${o.name}</p>
            <p class="text-muted text-xs">${o.members_count || 0} عضو</p>
          </div>
        </div>
      </a>
    `).join('');
  }

  const browseData = await App.fetch('/api/orgs?action=browse');
  if (browseData && browseData.orgs) {
    renderBrowseOrgs(browseData.orgs);
  }
}

async function searchOrgs(query) {
  if (!query || query.length < 2) return;
  const data = await App.fetch('/api/orgs?action=search&q=' + encodeURIComponent(query));
  if (data && data.orgs) {
    renderBrowseOrgs(data.orgs);
  }
}

function renderBrowseOrgs(orgs) {
  const container = document.getElementById('browse-orgs');
  if (orgs.length === 0) {
    container.innerHTML = '<div class="card"><div class="empty-state">لا توجد نتائج</div></div>';
    return;
  }
  container.innerHTML = orgs.map(o => `
    <a href="/org?id=${o.id}" class="card card-hover" style="display:block;text-decoration:none;margin-bottom:12px;">
      <div class="card-body" style="display:flex;align-items:center;gap:16px;">
        <div class="avatar" style="background:var(--bg-3);">
          <svg class="icon-lg" style="color:var(--cyan)"><use href="/public/icons/sprite.svg#icon-org"></use></svg>
        </div>
        <div style="flex:1;">
          <p style="font-size:15px;font-weight:600;">${o.name}</p>
          <p class="text-muted text-xs">${o.description || ''}</p>
        </div>
        <span class="badge">${o.members_count || 0} عضو</span>
      </div>
    </a>
  `).join('');
}

function showCreateOrg() {
  document.getElementById('create-org-modal').style.display = 'flex';
}
function hideCreateOrg() {
  document.getElementById('create-org-modal').style.display = 'none';
}

async function createOrg() {
  const name = document.getElementById('org-name').value.trim();
  const desc = document.getElementById('org-desc').value.trim();
  if (!name) { App.toast('ادخل اسم المنظمة', 'error'); return; }

  const res = await App.fetch('/api/orgs', {
    method: 'POST',
    body: JSON.stringify({ action: 'create', name, description: desc })
  });
  if (res && res.ok) {
    App.toast('تم انشاء المنظمة', 'success');
    hideCreateOrg();
    loadOrgs();
  } else {
    App.toast(res?.error || 'خطأ', 'error');
  }
}
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>
