<?php
$cards = is_array($cards ?? null) ? $cards : [];
$groups = [];
foreach ($cards as $card) {
    $groups[(string)$card['group']][] = $card;
}
$groupIcons = [
    'المبيعات' => 'fa-cart-shopping',
    'مرتجعات البيع' => 'fa-rotate-left',
    'المشتريات' => 'fa-cart-flatbed',
    'مرتجعات الشراء' => 'fa-rotate-right',
    'المخزون' => 'fa-boxes-stacked',
    'العملاء' => 'fa-users',
    'الموردين' => 'fa-truck',
    'الخزائن' => 'fa-vault',
    'البنوك' => 'fa-building-columns',
    'الشيكات' => 'fa-money-check',
    'المصروفات' => 'fa-receipt',
    'الأرباح' => 'fa-chart-line',
    'الضرائب والخصومات' => 'fa-percent',
    'التشغيل والرقابة' => 'fa-shield-halved',
    'الإدارة / Dashboard' => 'fa-gauge-high',
];
?>
<div class="reports-hub-compact">
  <div class="reports-hub-toolbar mb-3">
    <div class="d-flex align-items-center justify-content-between gap-3 flex-wrap mb-3">
      <div>
        <h4 class="mb-1 fw-black">مركز التقارير</h4>
        <div class="text-muted small fw-semibold">واجهة مختصرة للوصول السريع لأي تقرير بدون كروت كبيرة أو سكرول زائد.</div>
      </div>
      <span class="reports-total-pill"><i class="fa-solid fa-chart-pie ms-1"></i><?= count($cards) ?> تقرير</span>
    </div>

    <div class="reports-quick-line">
      <div class="reports-search-compact">
        <i class="fa-solid fa-magnifying-glass"></i>
        <input id="reportsHubSearch" type="search" class="form-control" placeholder="اكتب اسم التقرير أو كلمة منه..." autocomplete="off" autofocus>
      </div>
      <select id="reportsGroupSelect" class="form-select reports-group-select" aria-label="تصفية القسم">
        <option value="">كل الأقسام</option>
        <?php foreach (array_keys($groups) as $group): ?>
          <option value="<?= e($group) ?>"><?= e($group) ?> (<?= count($groups[$group]) ?>)</option>
        <?php endforeach; ?>
      </select>
      <button type="button" id="reportsClearFilters" class="btn btn-light border fw-bold reports-clear-btn">مسح</button>
    </div>

    <div class="reports-category-strip mt-3" id="reportsGroupFilters">
      <button type="button" class="active" data-group="">الكل</button>
      <?php foreach (array_keys($groups) as $group): ?>
        <button type="button" data-group="<?= e($group) ?>"><i class="fa-solid <?= e($groupIcons[$group] ?? 'fa-folder-open') ?> ms-1"></i><?= e($group) ?></button>
      <?php endforeach; ?>
    </div>
  </div>

  <?php if (!$cards): ?>
    <div class="alert alert-info rounded-4">لا توجد تقارير متاحة لصلاحيات المستخدم الحالي.</div>
  <?php endif; ?>

  <div id="reportsHubGrid" class="reports-compact-groups">
    <?php foreach ($groups as $group => $items): ?>
      <section class="reports-compact-section mb-3" data-group="<?= e($group) ?>">
        <button type="button" class="reports-compact-heading" data-bs-toggle="collapse" data-bs-target="#reports-section-<?= md5($group) ?>" aria-expanded="true">
          <span><i class="fa-solid <?= e($groupIcons[$group] ?? 'fa-folder-open') ?> ms-2"></i><?= e($group) ?></span>
          <small><?= count($items) ?> تقارير</small>
        </button>
        <div class="collapse show" id="reports-section-<?= md5($group) ?>">
          <div class="reports-list-grid">
            <?php foreach ($items as $card): ?>
              <?php $searchText = mb_strtolower(($card['title'] ?? '').' '.($card['description'] ?? '').' '.($card['tags'] ?? '').' '.($card['group'] ?? '')); ?>
              <div class="report-row-card" data-group="<?= e($group) ?>" data-search="<?= e($searchText) ?>">
                <a class="report-main-link" href="<?= e(url((string)$card['url'])) ?>" title="عرض التقرير">
                  <span class="report-mini-icon"><i class="fa-solid <?= e((string)$card['icon']) ?>"></i></span>
                  <span class="report-row-text">
                    <strong><?= e((string)$card['title']) ?></strong>
                    <small><?= e((string)$card['description']) ?></small>
                  </span>
                </a>

              </div>
            <?php endforeach; ?>
          </div>
        </div>
      </section>
    <?php endforeach; ?>
  </div>

  <div id="reportsEmptyState" class="reports-empty card border-0 shadow-sm text-center p-5" style="display:none">
    <div class="empty-icon"><i class="fa-solid fa-magnifying-glass"></i></div>
    <h5 class="fw-bold mt-3">لا توجد نتائج مطابقة</h5>
    <div class="text-muted">جرّب كلمة بحث مختلفة أو اختر قسم آخر.</div>
  </div>
</div>

<style>
.reports-hub-compact{--navy:#16324a;--muted:#64748b}.fw-black{font-weight:900}.reports-hub-toolbar{position:sticky;top:0;z-index:20;background:#fff;border:1px solid #e5edf4;border-radius:18px;padding:14px 16px;box-shadow:0 10px 26px rgba(15,23,42,.05)}.reports-total-pill{background:#eff6ff;color:var(--navy);border:1px solid #dbeafe;border-radius:999px;padding:7px 12px;font-weight:900;white-space:nowrap}.reports-quick-line{display:grid;grid-template-columns:minmax(260px,1fr) 220px auto;gap:10px;align-items:center}.reports-search-compact{position:relative}.reports-search-compact i{position:absolute;right:14px;top:50%;transform:translateY(-50%);color:#64748b}.reports-search-compact input{border-radius:14px;padding-right:42px;min-height:44px;border-color:#d8e4ef;font-weight:800}.reports-group-select,.reports-clear-btn{min-height:44px;border-radius:14px;font-weight:800}.reports-category-strip{display:flex;gap:8px;flex-wrap:wrap;overflow:visible;padding-bottom:0;scrollbar-width:auto}.reports-category-strip button{border:1px solid #d8e4ef;background:#f8fafc;color:#334155;border-radius:999px;padding:7px 12px;font-weight:900;font-size:12px;white-space:nowrap}.reports-category-strip button.active{background:var(--navy);color:#fff;border-color:var(--navy)}.reports-compact-section{background:#fff;border:1px solid #e8eef5;border-radius:16px;overflow:hidden;box-shadow:0 8px 22px rgba(15,23,42,.04)}.reports-compact-heading{width:100%;border:0;background:#f8fafc;padding:11px 14px;display:flex;align-items:center;justify-content:space-between;color:#0f172a;font-weight:900}.reports-compact-heading small{color:#64748b;font-weight:900}.reports-list-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;padding:10px}.report-row-card{display:flex;align-items:center;gap:10px;min-height:62px;border:1px solid #edf2f7;background:#fff;border-radius:14px;padding:8px 10px;transition:.14s ease}.report-row-card:hover{border-color:#cbd5e1;background:#f8fafc}.report-main-link{display:flex;align-items:center;gap:10px;text-decoration:none;color:inherit;min-width:0;flex:1;width:100%}.report-mini-icon{width:38px;height:38px;border-radius:12px;display:flex;align-items:center;justify-content:center;background:#eff6ff;color:#1d4ed8;flex:0 0 auto}.report-row-text{min-width:0;display:block}.report-row-text strong{display:block;font-weight:900;color:#0f172a;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.report-row-text small{display:block;color:#64748b;font-size:11px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:360px}.reports-empty{border-radius:20px}.empty-icon{width:54px;height:54px;border-radius:18px;margin:auto;background:#eff6ff;color:var(--navy);display:flex;align-items:center;justify-content:center;font-size:24px}@media(max-width:1200px){.reports-list-grid{grid-template-columns:1fr}.report-row-text small{max-width:520px}}@media(max-width:768px){.reports-hub-toolbar{position:static}.reports-quick-line{grid-template-columns:1fr}.reports-category-strip button{font-size:11px;padding:6px 10px}.report-row-text small{max-width:100%}}
</style>
<script>
(function(){
  const input=document.getElementById('reportsHubSearch');
  const select=document.getElementById('reportsGroupSelect');
  const clearBtn=document.getElementById('reportsClearFilters');
  const rows=[...document.querySelectorAll('.report-row-card')];
  const groups=[...document.querySelectorAll('.reports-compact-section')];
  const empty=document.getElementById('reportsEmptyState');
  const chips=[...document.querySelectorAll('#reportsGroupFilters button')];
  let activeGroup='';
  function normalize(v){return (v||'').trim().toLowerCase();}
  function setGroup(group){
    activeGroup=group||'';
    if(select) select.value=activeGroup;
    chips.forEach(b=>b.classList.toggle('active',(b.dataset.group||'')===activeGroup));
    apply();
  }
  function apply(){
    const q=normalize(input?.value);
    let visibleCount=0;
    rows.forEach(r=>{
      const okText=!q||(r.dataset.search||'').includes(q);
      const okGroup=!activeGroup||r.dataset.group===activeGroup;
      const show=okText&&okGroup;
      r.style.display=show?'':'none';
      if(show) visibleCount++;
    });
    groups.forEach(g=>{
      const groupHasVisible=[...g.querySelectorAll('.report-row-card')].some(r=>r.style.display!=='none');
      g.style.display=groupHasVisible?'':'none';
    });
    if(empty) empty.style.display=visibleCount?'none':'';
  }
  input?.addEventListener('input',apply);
  select?.addEventListener('change',()=>setGroup(select.value));
  clearBtn?.addEventListener('click',()=>{if(input) input.value=''; setGroup(''); input?.focus();});
  chips.forEach(btn=>btn.addEventListener('click',()=>setGroup(btn.dataset.group||'')));
})();
</script>
