<?php
$report = is_array($report ?? null) ? $report : [];
$filters = is_array($filters ?? null) ? $filters : [];
$columns = is_array($columns ?? null) ? $columns : [];
$rows = is_array($rows ?? null) ? $rows : [];
$summary = is_array($summary ?? null) ? $summary : [];
$lookups = is_array($lookups ?? null) ? $lookups : [];
$filterConfig = is_array($filter_config ?? null) ? $filter_config : [];
$fields = is_array($filterConfig['fields'] ?? null) ? $filterConfig['fields'] : ['from','to','party','item','warehouse','user','payment_mode','status','amount','q','per_page'];
$base = (string)($report['url'] ?? '');
$qs = $filters;
$qs['per_page'] = (int)($per_page ?? 25);
$hasRows = !empty($rows);
$hasField = static fn(string $field): bool => in_array($field, $fields, true);
$selectedText = static function(array $lookups, string $key): string {
    $row = is_array($lookups[$key] ?? null) ? $lookups[$key] : [];
    return (string)($row['text'] ?? '');
};
$partyLabel = (string)($filterConfig['party_label'] ?? 'بحث العميل / الطرف');
$partyLookupType = (string)($filterConfig['party_lookup_type'] ?? 'party');
$amountLabel = (string)($filterConfig['amount_label'] ?? 'مبلغ من / إلى');
$hint = (string)($filterConfig['hint'] ?? 'استخدم الفلاتر المناسبة ثم اضغط تطبيق.');
?>
<div class="report-unified-page report-compact-page">
  <div class="report-page-head mb-3">
    <div>
      <div class="report-breadcrumbs mb-2"><a href="<?= e(url('/admin/dashboard')) ?>">لوحة التحكم</a><span>/</span><a href="<?= e(url('/reports')) ?>">مركز التقارير</a><span>/</span><strong><?= e((string)($report['title'] ?? 'تقرير')) ?></strong></div>
      <h3 class="mb-1 fw-black"><?= e((string)($report['title'] ?? 'تقرير')) ?></h3>
      <div class="text-muted fw-semibold"><?= e((string)($report['description'] ?? '')) ?></div>
    </div>
    <a class="btn btn-light border fw-bold" href="<?= e(url('/reports')) ?>"><i class="fa-solid fa-arrow-right"></i> رجوع لمركز التقارير</a>
  </div>

  <form class="card report-filter-card p-3 mb-3" method="get" autocomplete="off">
    <div class="report-filter-grid">
      <?php if ($hasField('from')): ?><div><label class="form-label">من تاريخ</label><input type="date" class="form-control" name="from" value="<?= e((string)($filters['from'] ?? '')) ?>"></div><?php endif; ?>
      <?php if ($hasField('to')): ?><div><label class="form-label">إلى تاريخ</label><input type="date" class="form-control" name="to" value="<?= e((string)($filters['to'] ?? '')) ?>"></div><?php endif; ?>

      <?php if ($hasField('party')): ?>
      <div class="report-lookup" data-type="<?= e($partyLookupType) ?>">
        <label class="form-label"><?= e($partyLabel) ?></label>
        <input type="hidden" name="party_id" value="<?= (int)($filters['party_id'] ?? 0) ?>">
        <input type="search" class="form-control report-lookup-input" value="<?= e($selectedText($lookups, 'selected_party')) ?>" placeholder="اكتب حرفين من الاسم أو الكود أو الهاتف">
        <div class="report-lookup-menu"></div>
      </div>
      <?php endif; ?>

      <?php if ($hasField('item')): ?>
      <div class="report-lookup" data-type="item">
        <label class="form-label">بحث الصنف</label>
        <input type="hidden" name="item_id" value="<?= (int)($filters['item_id'] ?? 0) ?>">
        <input type="search" class="form-control report-lookup-input" value="<?= e($selectedText($lookups, 'selected_item')) ?>" placeholder="اكتب حرفين من اسم الصنف أو الباركود">
        <div class="report-lookup-menu"></div>
      </div>
      <?php endif; ?>

      <?php if ($hasField('warehouse')): ?>
      <div class="report-lookup" data-type="warehouse">
        <label class="form-label">بحث المخزن</label>
        <input type="hidden" name="warehouse_id" value="<?= (int)($filters['warehouse_id'] ?? 0) ?>">
        <input type="search" class="form-control report-lookup-input" value="<?= e($selectedText($lookups, 'selected_warehouse')) ?>" placeholder="اسم المخزن">
        <div class="report-lookup-menu"></div>
      </div>
      <?php endif; ?>


      <?php if ($hasField('cashbox')): ?>
      <div class="report-lookup" data-type="cashbox">
        <label class="form-label">بحث الخزنة</label>
        <input type="hidden" name="cashbox_id" value="<?= (int)($filters['cashbox_id'] ?? 0) ?>">
        <input type="search" class="form-control report-lookup-input" value="<?= e($selectedText($lookups, 'selected_cashbox')) ?>" placeholder="اسم الخزنة">
        <div class="report-lookup-menu"></div>
      </div>
      <?php endif; ?>

      <?php if ($hasField('bank_account')): ?>
      <div class="report-lookup" data-type="bank_account">
        <label class="form-label">بحث الحساب البنكي</label>
        <input type="hidden" name="bank_account_id" value="<?= (int)($filters['bank_account_id'] ?? 0) ?>">
        <input type="search" class="form-control report-lookup-input" value="<?= e($selectedText($lookups, 'selected_bank_account')) ?>" placeholder="اسم الحساب / البنك / رقم الحساب">
        <div class="report-lookup-menu"></div>
      </div>
      <?php endif; ?>

      <?php if ($hasField('user')): ?>
      <div class="report-lookup" data-type="user">
        <label class="form-label">بحث المستخدم</label>
        <input type="hidden" name="user_id" value="<?= (int)($filters['user_id'] ?? 0) ?>">
        <input type="search" class="form-control report-lookup-input" value="<?= e($selectedText($lookups, 'selected_user')) ?>" placeholder="اسم المستخدم">
        <div class="report-lookup-menu"></div>
      </div>
      <?php endif; ?>

      <?php if ($hasField('payment_mode')): ?><div><label class="form-label">طريقة الدفع</label><select class="form-select" name="payment_mode"><option value="">الكل</option><option value="cash" <?= ($filters['payment_mode']??'')==='cash'?'selected':'' ?>>نقدي</option><option value="credit" <?= ($filters['payment_mode']??'')==='credit'?'selected':'' ?>>آجل</option><option value="bank" <?= ($filters['payment_mode']??'')==='bank'?'selected':'' ?>>بنك</option></select></div><?php endif; ?>
      <?php if ($hasField('status')): ?><div><label class="form-label"><?= e((string)($filterConfig['status_label'] ?? 'الحالة')) ?></label><input type="text" class="form-control" name="status" value="<?= e((string)($filters['status'] ?? '')) ?>" placeholder="POSTED / DRAFT"></div><?php endif; ?>
      <?php if ($hasField('amount')): ?><div><label class="form-label"><?= e($amountLabel) ?></label><div class="d-flex gap-2"><input type="number" step="0.01" class="form-control" name="amount_min" value="<?= e((string)($filters['amount_min'] ?? '')) ?>" placeholder="من"><input type="number" step="0.01" class="form-control" name="amount_max" value="<?= e((string)($filters['amount_max'] ?? '')) ?>" placeholder="إلى"></div></div><?php endif; ?>
      <?php if ($hasField('diff_min')): ?><div><label class="form-label">فرق سعر أكبر من</label><input type="number" step="0.01" class="form-control" name="diff_min" value="<?= e((string)($filters['diff_min'] ?? '')) ?>" placeholder="مثال: 10"></div><?php endif; ?>
      <?php if ($hasField('inactive_days')): ?><div><label class="form-label">لم تتحرك منذ / يوم</label><input type="number" min="1" step="1" class="form-control" name="inactive_days" value="<?= e((string)($filters['inactive_days'] ?? '')) ?>" placeholder="90"></div><?php endif; ?>
      <?php if ($hasField('movement_type')): ?><div><label class="form-label">نوع الحركة</label><input type="text" class="form-control" name="movement_type" value="<?= e((string)($filters['movement_type'] ?? '')) ?>" placeholder="SALES_INV / PURCHASE_INV"></div><?php endif; ?>
      <?php if ($hasField('movement_sort')): ?><div><label class="form-label">ترتيب الحركة</label><select class="form-select" name="movement_sort"><option value="total" <?= ($filters['movement_sort']??'total')==='total'?'selected':'' ?>>إجمالي الحركة</option><option value="in" <?= ($filters['movement_sort']??'')==='in'?'selected':'' ?>>الوارد</option><option value="out" <?= ($filters['movement_sort']??'')==='out'?'selected':'' ?>>المنصرف</option></select></div><?php endif; ?>
      <?php if ($hasField('value')): ?><div><label class="form-label">قيمة من / إلى</label><div class="d-flex gap-2"><input type="number" step="0.01" class="form-control" name="value_min" value="<?= e((string)($filters['value_min'] ?? '')) ?>" placeholder="من"><input type="number" step="0.01" class="form-control" name="value_max" value="<?= e((string)($filters['value_max'] ?? '')) ?>" placeholder="إلى"></div></div><?php endif; ?>
      <?php if ($hasField('margin_max')): ?><div><label class="form-label">هامش أقل من</label><input type="number" step="0.01" class="form-control" name="margin_max" value="<?= e((string)($filters['margin_max'] ?? '')) ?>" placeholder="مثال: 5"></div><?php endif; ?>
      <?php if ($hasField('stock_flags')): ?><div class="report-filter-wide"><label class="form-label">خيارات المخزون</label><div class="d-flex gap-3 flex-wrap fw-bold"><label><input type="checkbox" name="non_zero" value="1" <?= (int)($filters['non_zero'] ?? 0)===1?'checked':'' ?>> فقط غير الصفري</label><label><input type="checkbox" name="negative_only" value="1" <?= (int)($filters['negative_only'] ?? 0)===1?'checked':'' ?>> فقط السالب</label><label><input type="checkbox" name="below_reorder" value="1" <?= (int)($filters['below_reorder'] ?? 0)===1?'checked':'' ?>> أقل من حد الطلب</label><label><input type="checkbox" name="show_cost" value="1" <?= (int)($filters['show_cost'] ?? 0)===1?'checked':'' ?>> عرض التكلفة</label></div></div><?php endif; ?>
      <?php if ($hasField('per_page')): ?><div><label class="form-label">عدد الصفوف</label><select class="form-select" name="per_page"><?php foreach ([25,50,100] as $n): ?><option value="<?= $n ?>" <?= (int)($per_page ?? 25)===$n?'selected':'' ?>><?= $n ?></option><?php endforeach; ?></select></div><?php endif; ?>
      <?php if ($hasField('q')): ?><div class="report-filter-wide"><label class="form-label">بحث نصي</label><input type="search" class="form-control" name="q" value="<?= e((string)($filters['q'] ?? '')) ?>" placeholder="رقم مستند / اسم / بيان"></div><?php endif; ?>
    </div>

    <div class="report-filter-actions mt-3">
      <button class="btn btn-primary fw-bold" type="submit"><i class="fa-solid fa-filter"></i> تطبيق</button>
      <a class="btn btn-light border fw-bold" href="<?= e(url($base)) ?>">مسح</a>
      <a class="btn btn-outline-secondary fw-bold" target="_blank" href="<?= e(url(($report['print_url'] ?? $base.'/print').'?'.http_build_query($qs + ['format'=>'a4']))) ?>"><i class="fa-solid fa-print"></i> طباعة</a>
      <a class="btn btn-outline-danger fw-bold" href="<?= e(url(($report['pdf_url'] ?? $base.'/pdf').'?'.http_build_query($qs))) ?>">PDF</a>
      <a class="btn btn-outline-success fw-bold" href="<?= e(url(($report['excel_url'] ?? $base.'/export').'?'.http_build_query($qs))) ?>">Excel</a>
    </div>
    <div class="form-text mt-3"><?= e($hint) ?></div>
  </form>

  <?php if ($summary): ?>
    <div class="report-summary-grid mb-3">
      <?php foreach ($summary as $label => $value): ?>
        <div class="report-stat-card">
          <div class="report-stat-accent"></div>
          <div class="report-stat-top">
            <div class="report-stat-label"><?= e((string)$label) ?></div>
            <div class="report-stat-icon"><i class="fa-solid fa-chart-simple"></i></div>
          </div>
          <div class="report-stat-value"><?= e((string)$value) ?></div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

  <div class="card p-3 report-results-card">
    <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-2">
      <div class="fw-bold">ملخص نتائج التقرير</div>
      <div class="text-muted small">عرض <?= (int)($from_row ?? 0) ?> - <?= (int)($to_row ?? 0) ?> من <?= (int)($total_rows ?? 0) ?></div>
    </div>
    <div class="table-responsive">
      <table class="table table-sm table-bordered align-middle table-hover mb-0">
        <thead class="table-light"><tr><?php foreach ($columns as $label): ?><th><?= e((string)$label) ?></th><?php endforeach; ?></tr></thead>
        <tbody>
          <?php if (!$hasRows): ?><tr><td colspan="<?= max(1,count($columns)) ?>" class="text-center text-muted py-4">لا توجد بيانات مطابقة للفلاتر الحالية</td></tr><?php endif; ?>
          <?php foreach ($rows as $r): ?><tr><?php foreach (array_keys($columns) as $key): ?><td><?= e((string)($r[$key] ?? '')) ?></td><?php endforeach; ?></tr><?php endforeach; ?>
        </tbody>
      </table>
    <?php if ((int)($total_pages ?? 1) > 1): ?>
      <?php
        $pageBaseQs = $filters;
        $pageBaseQs['per_page'] = (int)($per_page ?? 25);
        $currentPage = max(1, (int)($page ?? 1));
        $totalPages = max(1, (int)($total_pages ?? 1));
        $pages = array_unique(array_filter([1, $currentPage-1, $currentPage, $currentPage+1, $totalPages], static fn($x) => $x >= 1 && $x <= $totalPages));
        sort($pages);
      ?>
      <nav class="report-pagination mt-3" aria-label="صفحات التقرير">
        <ul class="pagination pagination-sm mb-0 justify-content-center flex-wrap">
          <li class="page-item <?= $currentPage <= 1 ? 'disabled' : '' ?>"><a class="page-link" href="<?= e(url($base.'?'.http_build_query($pageBaseQs + ['page'=>max(1,$currentPage-1)]))) ?>">السابق</a></li>
          <?php $last = 0; foreach ($pages as $pg): ?>
            <?php if ($last && $pg > $last + 1): ?><li class="page-item disabled"><span class="page-link">...</span></li><?php endif; ?>
            <li class="page-item <?= $pg === $currentPage ? 'active' : '' ?>"><a class="page-link" href="<?= e(url($base.'?'.http_build_query($pageBaseQs + ['page'=>$pg]))) ?>"><?= (int)$pg ?></a></li>
          <?php $last = $pg; endforeach; ?>
          <li class="page-item <?= $currentPage >= $totalPages ? 'disabled' : '' ?>"><a class="page-link" href="<?= e(url($base.'?'.http_build_query($pageBaseQs + ['page'=>min($totalPages,$currentPage+1)]))) ?>">التالي</a></li>
        </ul>
      </nav>
    <?php endif; ?>
    </div>
  </div>
</div>
<style>
.report-compact-page{--navy:#16324a;--muted:#64748b}.fw-black{font-weight:900}.report-page-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}.report-breadcrumbs{display:flex;align-items:center;gap:8px;color:#64748b;font-weight:700}.report-breadcrumbs a{text-decoration:none}.report-filter-card,.report-results-card{border-radius:18px;border:1px solid #e5edf4;box-shadow:0 8px 24px rgba(15,23,42,.04)}.report-filter-grid{display:grid;grid-template-columns:repeat(4,minmax(180px,1fr));gap:12px;align-items:end}.report-filter-grid .form-label{font-weight:900;color:#0f172a}.report-filter-grid .form-control,.report-filter-grid .form-select{min-height:44px;border-radius:14px;font-weight:700}.report-filter-wide{grid-column:span 2}.report-filter-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.report-filter-actions .btn{border-radius:12px;min-width:92px}.report-unified-page .table th{white-space:nowrap;font-weight:900;color:#0f172a}.report-unified-page .table td{vertical-align:middle}.report-summary-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px}.report-stat-card{position:relative;background:#fff;border:1px solid #e5edf4;border-radius:18px;padding:16px 18px;box-shadow:0 10px 24px rgba(15,23,42,.05);overflow:hidden;min-height:112px}.report-stat-accent{position:absolute;top:0;right:0;left:0;height:4px;background:linear-gradient(90deg,#2563eb,#60a5fa)}.report-stat-top{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px}.report-stat-label{font-size:.95rem;font-weight:800;color:#475569;line-height:1.4}.report-stat-icon{width:42px;height:42px;border-radius:14px;display:flex;align-items:center;justify-content:center;background:#eff6ff;color:#2563eb;border:1px solid #dbeafe;flex:0 0 auto}.report-stat-value{font-size:1.8rem;font-weight:900;color:#0f172a;line-height:1.1;letter-spacing:-.02em;direction:ltr;text-align:right}.report-lookup{position:relative}.report-lookup-menu{display:none;position:absolute;z-index:1050;left:8px;right:8px;top:100%;background:#fff;border:1px solid #dbe4ee;border-radius:12px;box-shadow:0 14px 30px rgba(15,23,42,.14);max-height:230px;overflow:auto;margin-top:4px}.report-lookup-menu.show{display:block}.report-lookup-item{display:block;width:100%;border:0;background:#fff;text-align:right;padding:9px 12px;font-weight:800;color:#0f172a}.report-lookup-item:hover{background:#eff6ff}.report-lookup-empty{padding:10px 12px;color:#64748b;font-weight:700}.report-lookup-input.cleared{border-color:#f59e0b;background:#fffbeb}.report-pagination .page-link{border-radius:10px;margin:2px;font-weight:800}.report-pagination .page-item.active .page-link{background:#16324a;border-color:#16324a}@media(max-width:1200px){.report-filter-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.report-filter-wide{grid-column:span 2}}@media(max-width:768px){.report-filter-grid{grid-template-columns:1fr}.report-filter-wide{grid-column:span 1}.report-summary-grid{grid-template-columns:1fr}.report-stat-card{min-height:auto}.report-stat-value{font-size:1.6rem}}
</style>
<script>
(function(){
  const endpoint = <?= json_encode(url('/reports/ajax/lookup'), JSON_UNESCAPED_UNICODE) ?>;
  document.querySelectorAll('.report-lookup').forEach(box => {
    const input = box.querySelector('.report-lookup-input');
    const hidden = box.querySelector('input[type="hidden"]');
    const menu = box.querySelector('.report-lookup-menu');
    let timer = null;
    function close(){ menu.classList.remove('show'); }
    function esc(value){ return String(value || '').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
    function clearHidden(){ hidden.value='0'; input.classList.add('cleared'); }
    input.addEventListener('input', () => {
      clearHidden();
      const q = input.value.trim();
      clearTimeout(timer);
      if (q.length < 2) { menu.innerHTML = '<div class="report-lookup-empty">اكتب حرفين على الأقل للبحث</div>'; menu.classList.add('show'); return; }
      timer = setTimeout(async () => {
        menu.innerHTML = '<div class="report-lookup-empty">جاري البحث...</div>'; menu.classList.add('show');
        try {
          const res = await fetch(endpoint + '?type=' + encodeURIComponent(box.dataset.type || '') + '&q=' + encodeURIComponent(q), {headers:{'X-Requested-With':'XMLHttpRequest'}});
          const rows = await res.json();
          if (!rows.length) { menu.innerHTML = '<div class="report-lookup-empty">لا توجد نتائج</div>'; return; }
          menu.innerHTML = rows.map(r => `<button type="button" class="report-lookup-item" data-id="${esc(r.id)}" data-text="${esc(r.text)}">${esc(r.text)}</button>`).join('');
        } catch(e) { menu.innerHTML = '<div class="report-lookup-empty">تعذر البحث الآن</div>'; }
      }, 220);
    });
    menu.addEventListener('click', e => {
      const btn = e.target.closest('.report-lookup-item');
      if (!btn) return;
      hidden.value = btn.dataset.id || '0';
      input.value = btn.dataset.text || btn.textContent.trim();
      input.classList.remove('cleared');
      close();
    });
    input.addEventListener('focus', () => { if (input.value.trim().length >= 2 && hidden.value === '0') menu.classList.add('show'); });
    document.addEventListener('click', e => { if (!box.contains(e.target)) close(); });
  });
})();
</script>
