<?php use App\Shared\Support\RoutePaths; ?>
<?php
$party_id = (int)($party_id ?? 0);
$party = $party ?? null;
$from = (string)($from ?? '');
$to = (string)($to ?? '');
$opening = (float)($opening ?? 0);
$closing = $closing ?? null;
$totals = is_array($totals ?? null) ? $totals : ['debit'=>0,'credit'=>0,'rows_count'=>0];
$filters = is_array($filters ?? null) ? $filters : [];
$docTypeOptions = is_array($doc_type_options ?? null) ? $doc_type_options : [];
$rows = is_array($rows ?? null) ? $rows : [];
$page_title = (string)($page_title ?? 'كشف حساب');
$role = (string)($role ?? 'party');
$running = $opening;
$basePath = $role === 'supplier' ? '/reports/parties/supplier-statement' : '/reports/parties/customer-statement';
$queryBase = $_GET;
$queryBase['role'] = $role;
if ($party_id > 0) { $queryBase['party_id'] = $party_id; }
$queryBase['from'] = $from;
$queryBase['to'] = $to;
$printQuery = $queryBase; $printQuery['format'] = 'a4'; unset($printQuery['page']);
$exportQuery = $queryBase; unset($exportQuery['page']);
$printUrl = url($basePath . '/print?' . http_build_query($printQuery));
$pdfUrl = url($basePath . '/pdf?' . http_build_query($printQuery));
$excelUrl = url($basePath . '/export?' . http_build_query($exportQuery));
$resetUrl = url($basePath);
$perPage = (int)($per_page ?? 50);
$totalRows = (int)($total_rows ?? 0);
$totalPages = (int)($total_pages ?? 1);
$currentPage = (int)($page ?? 1);
?>

<div class="statement-page">
  <div class="statement-hero card border-0 shadow-sm mb-3">
    <div class="card-body p-3 p-lg-4">
      <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
        <div>
          <div class="text-muted small fw-bold mb-1">Party Statement</div>
          <h3 class="mb-1 fw-black"><?= e($page_title) ?></h3>
          <div class="text-muted">فلترة سريعة، عرض مجزأ، وتصدير PDF / Excel مناسب للعربي.</div>
        </div>
        <div class="d-flex flex-wrap gap-2">
          <a class="btn btn-outline-secondary rounded-3 fw-bold" href="<?= e(url('/reports')) ?>"><i class="fa-solid fa-table-cells-large me-1"></i> مركز التقارير</a>
          <?php if ($party_id): ?>
            <a class="btn btn-outline-dark rounded-3 fw-bold" target="_blank" rel="noopener" href="<?= e($printUrl) ?>"><i class="fa-solid fa-print me-1"></i> طباعة</a>
            <a class="btn btn-dark rounded-3 fw-bold" href="<?= e($pdfUrl) ?>"><i class="fa-solid fa-file-pdf me-1"></i> PDF</a>
            <a class="btn btn-success rounded-3 fw-bold" href="<?= e($excelUrl) ?>"><i class="fa-solid fa-file-excel me-1"></i> Excel</a>
          <?php endif; ?>
          <?php if ($role === 'customer' && can('sales.receipts.create') && $party_id): ?>
            <a class="btn btn-primary rounded-3 fw-bold" href="<?= e(url('/sales/receipts/form?party_id='.(int)$party_id)) ?>"><i class="fa-solid fa-plus me-1"></i> سند قبض</a>
          <?php endif; ?>
          <?php if ($role === 'supplier' && can('supplier_payments.create') && $party_id): ?>
            <a class="btn btn-primary rounded-3 fw-bold" href="<?= e(url('/purchases/supplier-payments/form?party_id='.(int)$party_id)) ?>"><i class="fa-solid fa-plus me-1"></i> سداد مورد</a>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <form class="card border-0 shadow-sm filter-card mb-3" method="get" autocomplete="off">
    <div class="card-body p-3">
      <input type="hidden" name="role" value="<?= e($role) ?>">
      <div class="row g-2 align-items-end">
        <div class="col-lg-4 position-relative">
          <label class="form-label small text-muted fw-bold mb-1"><?= $role==='supplier' ? 'المورد' : 'العميل' ?></label>
          <input type="hidden" name="party_id" id="party_id" value="<?= $party_id ?>">
          <input type="text" class="form-control statement-input" id="party_search" placeholder="اكتب الاسم / الكود / الهاتف" value="<?= $party ? e($party['name'].' ('.$party['code'].')') : '' ?>">
          <div class="list-group position-absolute w-100 shadow-sm statement-suggest" id="party_results" style="z-index:40;display:none"></div>
        </div>
        <div class="col-6 col-lg-2">
          <label class="form-label small text-muted fw-bold mb-1">من</label>
          <input type="date" class="form-control statement-input" name="from" value="<?= e($from) ?>">
        </div>
        <div class="col-6 col-lg-2">
          <label class="form-label small text-muted fw-bold mb-1">إلى</label>
          <input type="date" class="form-control statement-input" name="to" value="<?= e($to) ?>">
        </div>
        <div class="col-6 col-lg-2">
          <label class="form-label small text-muted fw-bold mb-1">نوع الحركة</label>
          <select name="doc_type" class="form-select statement-input">
            <option value="">كل الأنواع</option>
            <?php foreach ($docTypeOptions as $key => $label): ?>
              <option value="<?= e((string)$key) ?>" <?= ((string)($filters['doc_type'] ?? '') === (string)$key) ? 'selected' : '' ?>><?= e((string)$label) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-6 col-lg-2">
          <label class="form-label small text-muted fw-bold mb-1">مدين / دائن</label>
          <select name="direction" class="form-select statement-input">
            <option value="" <?= ($filters['direction'] ?? '')===''?'selected':'' ?>>الكل</option>
            <option value="debit" <?= ($filters['direction'] ?? '')==='debit'?'selected':'' ?>>مدين فقط</option>
            <option value="credit" <?= ($filters['direction'] ?? '')==='credit'?'selected':'' ?>>دائن فقط</option>
          </select>
        </div>
        <div class="col-6 col-lg-2">
          <label class="form-label small text-muted fw-bold mb-1">رقم المستند</label>
          <input class="form-control statement-input" name="doc_no" value="<?= e((string)($filters['doc_no'] ?? '')) ?>" placeholder="مثال SI-">
        </div>
        <div class="col-6 col-lg-2">
          <label class="form-label small text-muted fw-bold mb-1">مبلغ من</label>
          <input class="form-control statement-input" name="amount_min" value="<?= e((string)($filters['amount_min'] ?? '')) ?>" inputmode="decimal">
        </div>
        <div class="col-6 col-lg-2">
          <label class="form-label small text-muted fw-bold mb-1">مبلغ إلى</label>
          <input class="form-control statement-input" name="amount_max" value="<?= e((string)($filters['amount_max'] ?? '')) ?>" inputmode="decimal">
        </div>
        <div class="col-lg-3">
          <label class="form-label small text-muted fw-bold mb-1">بحث داخل البيان</label>
          <input class="form-control statement-input" name="q" value="<?= e((string)($filters['q'] ?? '')) ?>" placeholder="ملاحظة / نوع / رقم">
        </div>
        <div class="col-6 col-lg-1">
          <label class="form-label small text-muted fw-bold mb-1">عدد</label>
          <select name="per_page" class="form-select statement-input">
            <?php foreach ([25,50,100] as $n): ?><option value="<?= $n ?>" <?= $perPage===$n?'selected':'' ?>><?= $n ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="col-lg-2 d-flex gap-2">
          <button class="btn btn-primary flex-fill rounded-3 fw-bold" type="submit"><i class="fa-solid fa-filter me-1"></i> تطبيق</button>
          <a class="btn btn-outline-secondary rounded-3 fw-bold" href="<?= e($resetUrl) ?>">مسح</a>
        </div>
      </div>
    </div>
  </form>

  <?php if (!$party): ?>
    <div class="empty-state card border-0 shadow-sm text-center p-5">
      <div class="empty-icon mb-3"><i class="fa-solid fa-magnifying-glass-chart"></i></div>
      <h5 class="fw-bold">اختر <?= $role==='supplier' ? 'مورد' : 'عميل' ?> لعرض كشف الحساب</h5>
      <div class="text-muted">ابدأ بكتابة الاسم أو الكود، ثم اضغط تطبيق. لن يتم تحميل بيانات كبيرة قبل اختيار الطرف.</div>
    </div>
  <?php else: ?>
    <div class="row g-3 mb-3">
      <div class="col-md-3"><div class="statement-stat"><span>رصيد أول المدة</span><strong><?= e(nf($opening)) ?></strong></div></div>
      <div class="col-md-3"><div class="statement-stat is-debit"><span>إجمالي مدين</span><strong><?= e(nf($totals['debit'] ?? 0)) ?></strong></div></div>
      <div class="col-md-3"><div class="statement-stat is-credit"><span>إجمالي دائن</span><strong><?= e(nf($totals['credit'] ?? 0)) ?></strong></div></div>
      <div class="col-md-3"><div class="statement-stat is-final"><span>رصيد آخر المدة</span><strong><?= e(nf($closing ?? $running)) ?></strong></div></div>
    </div>

    <div class="card border-0 shadow-sm content-card overflow-hidden">
      <div class="card-header bg-white py-3 d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div>
          <div class="fw-bold">حركة الحساب</div>
          <div class="text-muted small">عرض <?= (int)($from_row ?? 0) ?> - <?= (int)($to_row ?? 0) ?> من <?= $totalRows ?> حركة</div>
        </div>
        <div class="small text-muted">الفترة: <?= e($from) ?> إلى <?= e($to) ?></div>
      </div>
      <?php if ($totalRows > $perPage): ?>
      <div class="statement-limit-note mx-3 mb-3">
        <i class="fa-solid fa-circle-info"></i>
        المعروض في هذه الصفحة <?= (int)($from_row ?? 0) ?> - <?= (int)($to_row ?? 0) ?> فقط من إجمالي <?= $totalRows ?> حركة مطابقة للفلاتر. غيّر عدد الصفوف أو انتقل بين الصفحات، أما الطباعة وPDF وExcel فتستخدم نفس الفلاتر لكل الحركات المطابقة.
      </div>
      <?php endif; ?>
      <div class="table-responsive statement-table-wrap">
        <table class="table table-hover align-middle mb-0 statement-table">
          <thead>
            <tr>
              <th>التاريخ</th><th>النوع</th><th>المرجع</th><th>البيان</th><th class="text-end">مدين</th><th class="text-end">دائن</th><th class="text-end">الرصيد</th>
            </tr>
          </thead>
          <tbody>
            <tr class="opening-row"><td><?= e($from) ?></td><td><?= e(label_def('OPENING_BALANCE','statement_doc_type')) ?></td><td>—</td><td>رصيد أول المدة</td><td></td><td></td><td class="text-end fw-bold"><?= e(nf($opening)) ?></td></tr>
            <?php if (!$rows): ?><tr><td colspan="7" class="text-center text-muted py-4">لا توجد حركات مطابقة للفلاتر</td></tr><?php endif; ?>
            <?php foreach ($rows as $r): ?>
              <?php
                $d = (float)($r['debit'] ?? 0); $c = (float)($r['credit'] ?? 0); $running += ($d - $c);
                $docType = (string)($r['doc_type'] ?? '');
                $link = '';
                if ($docType === 'SALES_INV' || $docType === 'SALES_RCPT' || $docType === 'SALES_RECEIPT') $link = url('/sales/invoices/view?id='.(int)$r['doc_id']);
                elseif ($docType === 'RCPT') $link = url('/sales/receipts/view?id='.(int)$r['doc_id']);
                elseif ($docType === 'PAY') $link = url('/finance/cash-payments/view?id='.(int)$r['doc_id']);
                elseif ($docType === 'PAYMENT' || $docType === 'SUPPLIER_PAYMENT') $link = url('/purchases/supplier-payments/view?id='.(int)$r['doc_id']);
                elseif ($docType === 'PURCHASE_INV' || $docType === 'PURCHASE_PAY') $link = url('/purchases/invoices/view?id='.(int)$r['doc_id']);
                elseif ($docType === 'PURCHASE_RET') $link = url('/purchases/returns/view?id='.(int)$r['doc_id']);
                elseif ($docType === 'SALES_RET') $link = url('/sales/returns/view?id='.(int)$r['doc_id']);
                $displayNotes = ledger_entry_description($r);
              ?>
              <tr>
                <td><?= e((string)$r['doc_date']) ?><?php if (!empty($r['event_at'])): ?><div class="small text-muted"><?= e(date('H:i', strtotime((string)$r['event_at']))) ?></div><?php endif; ?></td>
                <td><span class="badge rounded-pill statement-type"><?= e(label_def($docType,'statement_doc_type')) ?></span></td>
                <td><?php if ($link): ?><a href="<?= e($link) ?>" class="fw-bold"><?= e((string)($r['doc_no'] ?? ledger_reference_label($r))) ?></a><?php else: ?><?= e((string)($r['doc_no'] ?? ledger_reference_label($r))) ?><?php endif; ?></td>
                <td class="text-muted"><?= e($displayNotes) ?></td>
                <td class="text-end debit-cell"><?= $d ? e(nf($d)) : '—' ?></td>
                <td class="text-end credit-cell"><?= $c ? e(nf($c)) : '—' ?></td>
                <td class="text-end fw-bold"><?= e(nf($running)) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php if ($totalPages > 1): ?>
      <div class="card-footer bg-white d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div class="text-muted small">صفحة <?= $currentPage ?> من <?= $totalPages ?></div>
        <div class="btn-group btn-group-sm">
          <?php for ($p=1; $p <= $totalPages; $p++): if ($p > 1 && $p < $totalPages && abs($p-$currentPage) > 2) { if ($p === 2 || $p === $totalPages-1) echo '<span class="btn btn-outline-secondary disabled">...</span>'; continue; } $q=$_GET; $q['page']=$p; ?>
            <a class="btn <?= $p===$currentPage?'btn-dark':'btn-outline-secondary' ?>" href="<?= e(url($basePath.'?'.http_build_query($q))) ?>"><?= $p ?></a>
          <?php endfor; ?>
        </div>
      </div>
      <?php endif; ?>
    </div>
  <?php endif; ?>
</div>

<style>
.fw-black{font-weight:900}.statement-hero{border-radius:20px;background:linear-gradient(135deg,#fff,#f8fafc)}.filter-card,.content-card,.empty-state{border-radius:18px}.statement-input{border-radius:12px;min-height:42px}.statement-suggest{border-radius:14px;overflow:hidden;margin-top:6px}.statement-suggest .list-group-item{padding:10px 12px}.empty-icon{width:64px;height:64px;margin:auto;border-radius:20px;background:#eff6ff;color:#16324a;display:flex;align-items:center;justify-content:center;font-size:28px}.statement-stat{height:100%;border:1px solid #e2e8f0;border-radius:18px;background:#fff;padding:16px;box-shadow:0 6px 18px rgba(15,23,42,.05)}.statement-stat span{display:block;color:#64748b;font-size:12px;font-weight:800;margin-bottom:8px}.statement-stat strong{font-size:22px;font-weight:900;color:#0f172a}.statement-stat.is-final{background:#16324a;border-color:#16324a}.statement-stat.is-final span,.statement-stat.is-final strong{color:#fff}.statement-table thead th{background:#16324a;color:#fff;border-color:#1f3c55;padding:12px 10px;font-size:13px;white-space:nowrap}.statement-table td{padding:11px 10px;border-color:#e5edf4}.statement-table-wrap{max-height:65vh}.statement-table thead{position:sticky;top:0;z-index:2}.statement-type{background:#eef6ff;color:#16324a;border:1px solid #d7e8fb;font-weight:800}.debit-cell{color:#0f766e;font-weight:800}.credit-cell{color:#b45309;font-weight:800}.opening-row td{background:#f8fafc;font-weight:700}.statement-limit-note{display:flex;align-items:flex-start;gap:8px;border:1px solid #bfdbfe;background:#eff6ff;color:#1e3a8a;border-radius:14px;padding:10px 12px;font-size:13px;font-weight:700}.statement-limit-note i{margin-top:3px}
</style>
<script>
(function(){
  const ps=document.getElementById('party_search'), pr=document.getElementById('party_results'), pid=document.getElementById('party_id');
  if(!ps||!pr||!pid) return;
  const searchUrl=<?= json_encode(url('/ajax/parties/search')) ?>; const searchType=<?= json_encode($role==='supplier'?'supplier':'customer') ?>;
  let t=null;
  function hide(){pr.style.display='none';pr.innerHTML='';}
  ps.addEventListener('input',()=>{
    clearTimeout(t); const q=ps.value.trim(); pid.value=0; if(q.length<2){hide();return;}
    t=setTimeout(async()=>{try{const r=await fetch(searchUrl+'?type='+encodeURIComponent(searchType)+'&q='+encodeURIComponent(q),{credentials:'same-origin'}); const data=await r.json(); pr.innerHTML='';
      data.slice(0,20).forEach(it=>{const a=document.createElement('a'); a.href='#'; a.className='list-group-item list-group-item-action'; const code=it.code?' ('+it.code+')':''; const phone=it.phone?' - '+it.phone:''; a.textContent=(it.name||'')+code+phone; a.onclick=(ev)=>{ev.preventDefault(); pid.value=it.id; ps.value=(it.name||'')+code; hide();}; pr.appendChild(a);});
      pr.style.display=data.length?'block':'none';}catch(e){hide();}},250);
  });
  document.addEventListener('click',e=>{if(!pr.contains(e.target)&&e.target!==ps) hide();});
})();
</script>
