<?php
$supplier_id = (int)($supplier_id ?? 0);
$supplier_query = $supplier_query ?? '';
$supplier = $supplier ?? null;
$from = $from ?? '';
$to = $to ?? '';
$opening = (float)($opening ?? 0);
$rows = $rows ?? [];
$running = $running ?? [];
$doc_type = strtoupper((string)($doc_type ?? ''));
$ref = (string)($ref ?? '');
$amount_min = (string)($amount_min ?? '');
$amount_max = (string)($amount_max ?? '');
$as_of = (string)($as_of ?? '');
$totals = $totals ?? ['debit'=>0,'credit'=>0,'closing'=>$opening];
$open_invoices = $open_invoices ?? [];

function doc_link(string $t, int $id): ?string {
  $t = strtoupper($t);
  return match($t) {
    'PURCHASE_INV' => $purchase_invoice_view_base_url ?? url('/purchases/invoices/view?id=' . $id),
    'PURCHASE_RET' => $purchase_return_view_base_url ?? url('/purchases/returns/view?id=' . $id),
    'PAYMENT' => $supplier_payment_view_base_url ?? url('/purchases/supplier-payments/view?id=' . $id),
    default => null,
  };
}

?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h4 class="mb-0">كشف حساب المورد</h4>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url('/parties/suppliers')) ?>">الموردين</a>
    <?php if ($supplier_id>0 && can('supplier_payments.create')): ?>
      <a class="btn btn-outline-success" href="<?= e(($supplier_payment_form_url ?? url('/purchases/supplier-payments/form')) . '?supplier_id='.$supplier_id) ?>">
        <i class="fa-solid fa-hand-holding-dollar me-1"></i>سداد
      </a>
    <?php endif; ?>
    <?php if ($supplier_id>0 && can('suppliers.statement.print')): ?>
      <a class="btn btn-outline-primary" target="_blank" href="<?= e(url('/reports/parties/supplier-statement/print?supplier_id='.$supplier_id.'&from='.urlencode($from).'&to='.urlencode($to).'&doc_type='.urlencode($doc_type).'&ref='.urlencode($ref).'&amount_min='.urlencode($amount_min).'&amount_max='.urlencode($amount_max))) ?>">
        <i class="fa-solid fa-print me-1"></i>طباعة
      </a>
    <?php endif; ?>
  </div>
</div>

<div class="card filter-card mb-3">
  <div class="card-body">
    <form class="row g-2 align-items-end" method="get">
      <div class="col-lg-4 position-relative">
        <label class="form-label">المورد</label>
        <input type="hidden" name="supplier_id" id="supplier_id" value="<?= $supplier_id ?>">
        <input type="text" class="form-control" id="supplier_query" name="supplier_query" value="<?= e($supplier_query) ?>" placeholder="اكتب اسم المورد / كود..." autocomplete="off" required>
        <div id="supplier_box" class="list-group position-absolute w-100 shadow-sm" style="z-index:50; display:none; max-height: 240px; overflow:auto;"></div>
      </div>
      <div class="col-lg-2">
        <label class="form-label">من</label>
        <input type="date" name="from" class="form-control" value="<?= e($from) ?>">
      </div>
      <div class="col-lg-2">
        <label class="form-label">إلى</label>
        <input type="date" name="to" class="form-control" value="<?= e($to) ?>">
      </div>
      <div class="col-lg-2">
        <label class="form-label">نوع الحركة</label>
        <select name="doc_type" class="form-select">
          <option value="" <?= $doc_type===''?'selected':'' ?>>الكل</option>
          <option value="PURCHASE_INV" <?= $doc_type==='PURCHASE_INV'?'selected':'' ?>>فواتير الشراء</option>
          <option value="PURCHASE_RET" <?= $doc_type==='PURCHASE_RET'?'selected':'' ?>>مرتجعات الشراء</option>
          <option value="PAYMENT" <?= $doc_type==='PAYMENT'?'selected':'' ?>>المدفوعات</option>
        </select>
      </div>
      <div class="col-lg-2 d-grid">
        <button class="btn btn-primary"><i class="fa-solid fa-magnifying-glass me-1"></i>عرض</button>
      </div>

      <div class="col-12">
        <div class="row g-2">
          <div class="col-md-6">
            <label class="form-label">بحث بالمرجع</label>
            <input type="text" name="ref" class="form-control" value="<?= e($ref) ?>" placeholder="رقم المستند...">
          </div>
          <div class="col-md-3">
            <label class="form-label">المبلغ من</label>
            <input type="number" step="0.01" min="0" name="amount_min" class="form-control" value="<?= e($amount_min) ?>" placeholder="0.00">
          </div>
          <div class="col-md-3">
            <label class="form-label">المبلغ إلى</label>
            <input type="number" step="0.01" min="0" name="amount_max" class="form-control" value="<?= e($amount_max) ?>" placeholder="0.00">
          </div>
        </div>
      </div>
    </form>
  </div>
</div>

<?php if ($supplier_id>0 && $supplier): ?>
  <div class="row g-3">
    <div class="col-md-4">
      <div class="card content-card">
        <div class="card-header fw-bold">بيانات المورد</div>
        <div class="card-body">
          <div class="mb-2"><span class="text-muted">الاسم:</span> <strong><?= e((string)$supplier['name']) ?></strong></div>
          <div class="mb-2"><span class="text-muted">الكود:</span> <strong><?= e((string)$supplier['code']) ?></strong></div>
          <div><span class="text-muted">الرصيد الافتتاحي حتى بداية الفترة:</span> <strong><?= e(format_money($opening)) ?></strong></div>
        </div>
      </div>

      <div class="card content-card mt-3">
        <div class="card-header fw-bold">ملخص الفترة</div>
        <div class="card-body">
          <div class="d-flex justify-content-between mb-2"><span class="text-muted">إجمالي المدين</span><strong><?= e(format_money((float)$totals['debit'])) ?></strong></div>
          <div class="d-flex justify-content-between mb-2"><span class="text-muted">إجمالي الدائن</span><strong><?= e(format_money((float)$totals['credit'])) ?></strong></div>
          <hr>
          <?php
            $cl = (float)$totals['closing'];
            $clClass = $cl>0?'text-danger':($cl<0?'text-success':'text-muted');
            $clTxt = $cl>0 ? 'عليه' : ($cl<0 ? 'له' : 'متوازن');
          ?>
          <div class="d-flex justify-content-between align-items-center">
            <span class="text-muted">الرصيد الختامي</span>
            <div class="text-end">
              <div class="fw-bold fs-5 <?= $clClass ?>"><?= e(format_money($cl)) ?></div>
              <span class="badge <?= $cl>0?'bg-danger':($cl<0?'bg-success':'bg-secondary') ?>"><?= e($clTxt) ?></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-8">
      <div class="card content-card">
        <div class="card-header fw-bold">الحركة</div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-bordered table-hover mb-0">
              <thead class="table-light">
                <tr>
                  <th style="width:110px">التاريخ</th>
                  <th style="width:140px">النوع</th>
                  <th style="width:160px">المرجع</th>
                  <th>ملاحظات</th>
                  <th style="width:120px" class="text-end">مدين</th>
                  <th style="width:120px" class="text-end">دائن</th>
                  <th style="width:140px" class="text-end">الرصيد</th>
                </tr>
              </thead>
              <tbody>
                <tr class="table-secondary">
                  <td colspan="6" class="fw-bold">رصيد افتتاحي</td>
                  <?php $ob=(float)$opening; $obClass=$ob>0?'text-danger':($ob<0?'text-success':'text-muted'); ?>
                  <td class="text-end fw-bold <?= $obClass ?>"><?= e(format_money($ob)) ?></td>
                </tr>

                <?php if (!$rows): ?>
                  <tr><td colspan="7" class="text-center text-muted py-4">لا توجد حركة في الفترة</td></tr>
                <?php else: ?>
                  <?php foreach ($rows as $r): ?>
                    <tr>
                      <td><?= e(substr((string)$r['doc_date'],0,10)) ?></td>
                      <td><?= e(reference_type_label((string)$r['doc_type'])) ?></td>
                      <td>
                        <?php $href = doc_link((string)$r['doc_type'], (int)$r['doc_id']); ?>
                        <?php if ($href): ?>
                          <a href="<?= e($href) ?>" class="text-decoration-none" target="_blank"><?= e(human_reference_label((string)$r['doc_type'], (int)$r['doc_id'], (string)($r['doc_no'] ?? ''))) ?></a>
                        <?php else: ?>
                          <?= e(human_reference_label((string)$r['doc_type'], (int)$r['doc_id'], (string)($r['doc_no'] ?? ''))) ?>
                        <?php endif; ?>
                      </td>
                      <td><?= e(trim((string)($r['notes'] ?? '')) ?: human_reference_label((string)$r['doc_type'], (int)$r['doc_id'], (string)($r['doc_no'] ?? ''))) ?></td>
                      <td class="text-end"><?= (float)$r['debit']>0 ? e(format_money((float)$r['debit'])) : '' ?></td>
                      <td class="text-end"><?= (float)$r['credit']>0 ? e(format_money((float)$r['credit'])) : '' ?></td>
                      <?php $rb=(float)($running[(int)$r['id']] ?? $opening); $rbClass=$rb>0?'text-danger':($rb<0?'text-success':'text-muted'); ?>
                      <td class="text-end fw-bold <?= $rbClass ?>"><?= e(format_money($rb)) ?></td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <?php if ($open_invoices): ?>
        <div class="card content-card mt-3">
          <div class="card-header fw-bold">فواتير مفتوحة حتى تاريخ: <?= e($as_of) ?></div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-bordered table-hover mb-0">
                <thead class="table-light">
                  <tr>
                    <th style="width:160px">رقم الفاتورة</th>
                    <th style="width:120px">التاريخ</th>
                    <th class="text-end" style="width:140px">إجمالي</th>
                    <th class="text-end" style="width:140px">مرتجع</th>
                    <th class="text-end" style="width:140px">مسدد</th>
                    <th class="text-end" style="width:160px">المتبقي</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $sumRemain = 0.0; foreach ($open_invoices as $inv): $sumRemain += (float)$inv['remaining']; ?>
                    <tr>
                      <td><a href="<?= e(($purchase_invoice_view_base_url ?? url('/purchases/invoices/view')) . '?id='.(int)$inv['id']) ?>" target="_blank" class="text-decoration-none"><?= e((string)$inv['inv_no']) ?></a></td>
                      <td><?= e((string)$inv['inv_date']) ?></td>
                      <td class="text-end"><?= e(format_money((float)$inv['inv_total'])) ?></td>
                      <td class="text-end"><?= e(format_money((float)$inv['ret_total'])) ?></td>
                      <td class="text-end"><?= e(format_money((float)$inv['paid_total'])) ?></td>
                      <td class="text-end fw-bold"><?= e(format_money((float)$inv['remaining'])) ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
                <tfoot class="table-secondary">
                  <tr>
                    <th colspan="5" class="text-end">إجمالي المتبقي</th>
                    <th class="text-end fw-bold"><?= e(format_money($sumRemain)) ?></th>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>
      <?php endif; ?>
    </div>
  </div>
<?php endif; ?>

<script>
(function(){
  const supQ = document.getElementById('supplier_query');
  const supId = document.getElementById('supplier_id');
  const box = document.getElementById('supplier_box');
  let t=null;

  function hide(){ box.style.display='none'; box.innerHTML=''; }
  function show(){ box.style.display='block'; }

  supQ.addEventListener('input', ()=>{
    clearTimeout(t);
    const val = supQ.value.trim();
    supId.value = '';
    if (val.length < 1) { hide(); return; }
    t = setTimeout(async ()=>{
      try{
        const res = await fetch(<?= json_encode(url('/ajax/parties/search?type=supplier')) ?> + '&q=' + encodeURIComponent(val));
        const items = await res.json();
        if (!items || !items.length){ hide(); return; }
        box.innerHTML = items.map(it => `
          <button type="button" class="list-group-item list-group-item-action" data-id="${it.id}">
            <div class="fw-bold">${it.name}</div>
            <div class="small text-muted">${it.code || ''}</div>
          </button>`).join('');
        show();
      }catch(e){ hide(); }
    }, 200);
  });

  box.addEventListener('click', (e)=>{
    const btn = e.target.closest('button[data-id]');
    if (!btn) return;
    supId.value = btn.getAttribute('data-id');
    supQ.value = btn.querySelector('.fw-bold').textContent.trim();
    hide();
  });

  document.addEventListener('click', (e)=>{
    if (!box.contains(e.target) && e.target !== supQ) hide();
  });
})();
</script>
