<?php use App\Modules\Sales\Application\Services\SalesReceiptsRouteContext; ?>
<?php
// variables: $receipt, $party, $cashboxes, $bankAccounts, $errors
?>

<div class="page-actions-bar">
  <a class="btn btn-outline-secondary btn-back" data-shortcut="back" href="<?= e($routeContext['index'] ?? SalesReceiptsRouteContext::index()) ?>">رجوع</a>
</div>

<?php if (!empty($errors)): ?>
  <div class="alert alert-danger">
    <ul class="mb-0">
      <?php foreach ($errors as $er): ?>
        <li><?= e($er) ?></li>
      <?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>

<form method="post" class="form-shell" autocomplete="off">
  <div class="card content-card"><div class="card-body">
  <?= csrf_field() ?>

  <div class="row g-3">
    <div class="col-md-3">
      <label class="form-label">التاريخ</label>
      <input type="date" class="form-control" name="receipt_date" value="<?= e((string)$receipt['receipt_date']) ?>">
    </div>

    <div class="col-md-6 position-relative">
      <label class="form-label">الطرف</label>
      <input type="hidden" name="party_id" id="party_id" value="<?= (int)($receipt['party_id'] ?? 0) ?>">
      <input type="text" class="form-control" id="party_search" placeholder="ابحث بالاسم/الكود/الموبايل" value="<?= $party ? e($party['name'].' ('.$party['code'].')') : '' ?>">
      <div class="list-group position-absolute w-100 shadow-sm" id="party_results" style="z-index: 20; display:none"></div>
    </div>

    <div class="col-md-3">
      <label class="form-label">القيمة</label>
      <input type="number" min="0" step="0.01" class="form-control text-end" name="amount" value="<?= e((string)$receipt['amount']) ?>">
    </div>

    <div class="col-md-3">
      <label class="form-label">التحصيل إلى</label>
      <select class="form-select" name="account_source_type" id="account_source_type">
        <?php $ast = (string)($receipt['account_source_type'] ?? 'cashbox'); ?>
        <option value="cashbox" <?= ($ast==='cashbox')?'selected':'' ?>>خزنة</option>
        <option value="bank_account" <?= ($ast==='bank_account')?'selected':'' ?>>حساب بنكي</option>
      </select>
    </div>

    <div class="col-md-3" id="cashbox_wrap">
      <label class="form-label">الخزنة</label>
      <select class="form-select" name="cashbox_id" id="cashbox_id">
        <?php foreach (($cashboxes ?? []) as $cb): ?>
          <option value="<?= (int)$cb['id'] ?>" <?= ((int)($receipt['cashbox_id'] ?? 0) === (int)$cb['id']) ? 'selected' : '' ?>><?= e($cb['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="col-md-3" id="bank_account_wrap" style="display:none">
      <label class="form-label">الحساب البنكي</label>
      <select class="form-select" name="bank_account_id" id="bank_account_id">
        <?php foreach (($bankAccounts ?? []) as $ba): ?>
          <option value="<?= (int)$ba['id'] ?>" <?= ((int)($receipt['bank_account_id'] ?? 0) === (int)$ba['id']) ? 'selected' : '' ?>><?= e($ba['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="col-md-3">
      <label class="form-label">طريقة الدفع</label>
      <select class="form-select" name="pay_method" id="pay_method">
        <?php $pm = strtolower((string)($receipt['pay_method'] ?? 'cash')); ?>
        <option value="cash" <?= ($pm==='cash')?'selected':'' ?>>نقدي</option>
        <option value="bank_transfer" <?= ($pm==='bank_transfer')?'selected':'' ?>>تحويل بنكي</option>
        <option value="cheque" <?= ($pm==='cheque')?'selected':'' ?>>شيك</option>
      </select>
    </div>

    <div class="col-md-3" id="ref_no_wrap">
      <label class="form-label">رقم مرجعي</label>
      <input type="text" class="form-control" name="ref_no" value="<?= e((string)$receipt['ref_no']) ?>">
    </div>

    <div class="col-12" id="cheque_fields" style="display:none">
      <div class="embedded-light">
        <div class="row g-3">
          <div class="col-md-3">
            <label class="form-label">رقم الشيك</label>
            <input type="text" class="form-control" name="cheque_no" value="<?= e((string)($receipt['cheque_no'] ?? '')) ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">تاريخ الاستحقاق</label>
            <input type="date" class="form-control" name="cheque_due_date" value="<?= e((string)($receipt['cheque_due_date'] ?? '')) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">اسم المستفيد</label>
            <input type="text" class="form-control" name="beneficiary_name" value="<?= e((string)($receipt['beneficiary_name'] ?? '')) ?>" placeholder="مثال: <?= e(($config['app']['name'] ?? '')) ?>">
          </div>
        </div>
      </div>
    </div>

    <div class="col-12" id="bank_fields" style="display:none">
      <div class="embedded-light">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">اسم البنك</label>
            <input type="text" class="form-control" name="bank_name" value="<?= e((string)($receipt['bank_name'] ?? '')) ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">رقم مرجع التحويل</label>
            <input type="text" class="form-control" name="transfer_ref" value="<?= e((string)($receipt['transfer_ref'] ?? '')) ?>">
          </div>
          <div class="col-md-4">
            <label class="form-label">تاريخ التحويل</label>
            <input type="date" class="form-control" name="transfer_date" value="<?= e((string)($receipt['transfer_date'] ?? '')) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">اسم المُحوّل</label>
            <input type="text" class="form-control" name="sender_name" value="<?= e((string)($receipt['sender_name'] ?? '')) ?>">
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-6">
      <label class="form-label">ملاحظات</label>
      <input type="text" class="form-control" name="notes" value="<?= e((string)$receipt['notes']) ?>">
    </div>
  </div></div>

  <div class="card content-card sticky-actions"><div class="card-body d-flex gap-2 justify-content-end flex-wrap">
    <button class="btn btn-primary btn-save" data-shortcut="save" type="submit"><i class="fa-solid fa-check"></i> حفظ <span class="shortcut-hint">F7</span></button>
    <a class="btn btn-outline-dark btn-back" data-shortcut="back" href="<?= e($routeContext['index'] ?? SalesReceiptsRouteContext::index()) ?>">إلغاء</a>
  </div></div>
</form>

<script>
  const payMethod = document.getElementById('pay_method');
  const chequeFields = document.getElementById('cheque_fields');
  const bankFields = document.getElementById('bank_fields');
  const accountSource = document.getElementById('account_source_type');
  const cashboxWrap = document.getElementById('cashbox_wrap');
  const bankAccountWrap = document.getElementById('bank_account_wrap');

  function syncPayMethodUI() {
    const v = (payMethod.value || 'cash');
    chequeFields.style.display = (v === 'cheque') ? 'block' : 'none';
    bankFields.style.display = (v === 'bank_transfer') ? 'block' : 'none';
  }
  function syncAccountSourceUI() {
    const v = (accountSource.value || 'cashbox');
    cashboxWrap.style.display = (v === 'cashbox') ? 'block' : 'none';
    bankAccountWrap.style.display = (v === 'bank_account') ? 'block' : 'none';
  }
  payMethod.addEventListener('change', syncPayMethodUI);
  accountSource.addEventListener('change', syncAccountSourceUI);
  syncPayMethodUI();
  syncAccountSourceUI();

  const partySearch = document.getElementById('party_search');
  const partyResults = document.getElementById('party_results');
  const partyId = document.getElementById('party_id');
  const partySearchUrl = <?= json_encode(url('/ajax/parties/search?type=all')) ?>;

  let partyTimer = null;
  partySearch.addEventListener('input', () => {
    clearTimeout(partyTimer);
    const q = partySearch.value.trim();
    partyId.value = 0;
    if (!q) { partyResults.style.display='none'; partyResults.innerHTML=''; return; }
    partyTimer = setTimeout(async () => {
      try {
        const r = await fetch(partySearchUrl + '&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');
        partyResults.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();
            partyId.value = it.id;
            partySearch.value = a.textContent;
            partyResults.style.display='none';
          });
          partyResults.appendChild(a);
        });
        partyResults.style.display = data.length ? 'block' : 'none';
      } catch (e) {
        partyResults.innerHTML = '<div class="list-group-item text-danger">تعذر تحميل الأطراف.</div>';
        partyResults.style.display = 'block';
      }
    }, 250);
  });

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