<?php
// variables: $customer_id, $customer, $from, $to, $opening, $closing, $rows
$running = $opening ?? 0;
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h4 class="mb-0">كشف حساب العميل</h4>
  <?php if (can('sales.receipts.create') && !empty($customer_id)): ?>
    <a class="btn btn-primary" href="<?= e(url('/sales/receipts/form?customer_id='.(int)$customer_id)) ?>"><i class="fa-solid fa-plus"></i> سند قبض للعميل</a>
  <?php endif; ?>
</div>

<form class="card p-3 mb-3" method="get" autocomplete="off">
  <div class="row g-2 align-items-end">
    <div class="col-md-6 position-relative">
      <label class="form-label">العميل</label>
      <input type="hidden" name="customer_id" id="customer_id" value="<?= (int)$customer_id ?>">
      <input type="text" class="form-control" id="customer_search" placeholder="ابحث بالاسم/الكود/الموبايل" value="<?= $customer ? e($customer['name'].' ('.$customer['code'].')') : '' ?>">
      <div class="list-group position-absolute w-100 shadow-sm" id="customer_results" style="z-index: 20; display:none"></div>
    </div>

    <div class="col-md-2">
      <label class="form-label">من</label>
      <input type="date" class="form-control" name="from" value="<?= e($from) ?>">
    </div>
    <div class="col-md-2">
      <label class="form-label">إلى</label>
      <input type="date" class="form-control" name="to" value="<?= e($to) ?>">
    </div>
    <div class="col-md-2 d-flex gap-2">
      <button class="btn btn-outline-primary w-100" type="submit">عرض</button>
      <a class="btn btn-outline-secondary" href="<?= e(url('/reports/parties/customer-statement')) ?>">مسح</a>
    </div>
  </div>

  <div class="form-text mt-2">
    المبدأ: الرصيد = رصيد افتتاحي + (مدين - دائن). المدين يزيد مديونية العميل، والدائن يقللها.
  </div>
</form>

<?php if ($customer): ?>
  <div class="row g-3 mb-3">
    <div class="col-md-4">
      <div class="small-box text-bg-secondary">
        <div class="inner">
          <h3><?= e(nf($opening ?? 0)) ?></h3>
          <p>رصيد أول المدة</p>
        </div>
        <div class="icon"><i class="fa-solid fa-wallet"></i></div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="small-box text-bg-success">
        <div class="inner">
          <h3><?= e(nf($closing ?? 0)) ?></h3>
          <p>رصيد آخر المدة</p>
        </div>
        <div class="icon"><i class="fa-solid fa-scale-balanced"></i></div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="small-box text-bg-primary">
        <div class="inner">
          <h3><?= e(count($rows)) ?></h3>
          <p>عدد الحركات</p>
        </div>
        <div class="icon"><i class="fa-solid fa-list"></i></div>
      </div>
    </div>
  </div>

  <div class="card p-3">
    <div class="table-responsive">
      <table class="table table-sm table-bordered align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>التاريخ</th>
            <th>النوع</th>
            <th>رقم المستند</th>
            <th class="text-end">مدين</th>
            <th class="text-end">دائن</th>
            <th class="text-end">الرصيد</th>
            <th>ملاحظات</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td colspan="5" class="text-muted">رصيد أول المدة</td>
            <td class="text-end fw-bold"><?= e(nf($opening ?? 0)) ?></td>
            <td></td>
          </tr>

          <?php if (empty($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'] ?? '');
              $docNo = (string)($r['doc_no'] ?? '');
              $link = '';
              if ($docType === 'SALES_INV') {
                $link = url('/sales/invoices/view?id='.(int)$r['doc_id']);
              } elseif ($docType === 'CUST_RCPT') {
                $link = url('/sales/receipts/view?id='.(int)$r['doc_id']);
              }
            ?>
            <tr>
              <td><?= e($r['doc_date']) ?></td>
              <td><?= e($docType) ?></td>
              <td>
                <?php if ($link): ?>
                  <a href="<?= e($link) ?>" class="fw-bold"><?= e($docNo) ?></a>
                <?php else: ?>
                  <?= e($docNo) ?>
                <?php endif; ?>
              </td>
              <td class="text-end"><?= $d ? e(nf($d)) : '' ?></td>
              <td class="text-end"><?= $c ? e(nf($c)) : '' ?></td>
              <td class="text-end fw-bold"><?= e(nf($running)) ?></td>
              <td class="text-muted"><?= e($r['notes'] ?? '') ?></td>
            </tr>
          <?php endforeach; ?>

          <tr class="table-light">
            <td colspan="5" class="fw-bold">رصيد آخر المدة</td>
            <td class="text-end fw-bold"><?= e(nf($closing ?? $running)) ?></td>
            <td></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
<?php endif; ?>

<script>
  const cs = document.getElementById('customer_search');
  const cr = document.getElementById('customer_results');
  const cid = document.getElementById('customer_id');
  const customerSearchUrl = <?= json_encode(url('/ajax/parties/search?type=customer')) ?>;

  let customerTimer = null;
  cs.addEventListener('input', () => {
    clearTimeout(customerTimer);
    const q = cs.value.trim();
    cid.value = 0;
    // Keep behavior consistent with Sales Invoices screen:
    // allow searching even with 1 character (some customer names/codes can be 1 char).
    if (!q) { cr.style.display='none'; cr.innerHTML=''; return; }
    customerTimer = setTimeout(async () => {
      try {
        const r = await fetch(customerSearchUrl + '&q=' + encodeURIComponent(q), { credentials: 'same-origin' });
        if (!r.ok) throw new Error('HTTP ' + r.status);
        const data = await r.json();
        if (!Array.isArray(data)) throw new Error('Invalid JSON');
      cr.innerHTML = '';
      data.forEach(it => {
        const a = document.createElement('a');
        a.href = '#';
        a.className = 'list-group-item list-group-item-action';
        a.textContent = (it.name || '') + ' (' + (it.code || '') + ')';
        a.addEventListener('click', (ev) => {
          ev.preventDefault();
          cid.value = it.id;
          cs.value = a.textContent;
          cr.style.display='none';
        });
        cr.appendChild(a);
      });
      cr.style.display = data.length ? 'block' : 'none';
      } catch (e) {
        cr.innerHTML = '<div class="list-group-item text-danger">تعذر تحميل العملاء. افتح الرابط للتأكد: ' + customerSearchUrl + '</div>';
        cr.style.display = 'block';
      }
    }, 250);
  });

  document.addEventListener('click', (e) => {
    if (!cr.contains(e.target) && e.target !== cs) {
      cr.style.display='none';
    }
  });
</script>
