<?php
// variables: $cashboxes, $bankAccounts, $expenseItems, $openCustodies, $form, $errors
?>

<div class="page-actions-bar">
  <a class="btn btn-outline-secondary btn-back" data-shortcut="back" href="<?= e(url($cash_payments_url ?? '/finance/cash-payments')) ?>">رجوع</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="voucher_date" value="<?= e((string)$form['voucher_date']) ?>">
    </div>

    <div class="col-md-3">
      <label class="form-label">نوع السند</label>
      <?php $pt = (string)($form['payment_type'] ?? 'party'); ?>
      <select class="form-select" name="payment_type" id="payment_type">
        <option value="party" <?= ($pt==='party')?'selected':'' ?>>سداد طرف</option>
        <option value="expense" <?= ($pt==='expense')?'selected':'' ?>>مصروف</option>
      </select>
    </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)($form['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">
      <label class="form-label">الطريقة</label>
      <?php $pm = strtolower((string)($form['pay_method'] ?? 'cash')); ?>
      <select class="form-select" name="pay_method">
        <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-4" 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)$form['cashbox_id'] === (int)$cb['id']) ? 'selected' : '' ?>><?= e($cb['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="col-md-4" 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)($form['bank_account_id'] ?? 0) === (int)$ba['id']) ? 'selected' : '' ?>><?= e($ba['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    </div>


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

    <div class="col-md-6" id="party_wrap">
      <label class="form-label">الطرف</label>
      <input type="hidden" name="party_id" id="party_id" value="<?= e((string)($form['party_id'] ?? '0')) ?>">
      <input type="hidden" name="party_name" id="party_name" value="<?= e((string)($form['party_name'] ?? '')) ?>">
      <input type="text" class="form-control" id="party_query" placeholder="ابحث عن المورد/الطرف..." autocomplete="off" value="<?= e((string)($form['party_name'] ?? '')) ?>">
      <div class="list-group position-absolute w-100" id="party_box" style="z-index:1050; display:none"></div>
      
    </div>

    <div class="col-md-6" id="expense_wrap" style="display:none">
      <label class="form-label">بند المصروف</label>
      <select class="form-select" name="expense_item_id" id="expense_item_id">
        <option value="0">اختر بند المصروف</option>
        <?php foreach (($expenseItems ?? []) as $ei): ?>
          <option value="<?= (int)$ei['id'] ?>" <?= ((int)($form['expense_item_id'] ?? 0) === (int)$ei['id']) ? 'selected' : '' ?>><?= e($ei['category_name'] . ' / ' . $ei['name']) ?></option>
        <?php endforeach; ?>
      </select>
      
    </div>

    <div class="col-md-6">
      <label class="form-label">المستفيد/الجهة</label>
      <input type="text" class="form-control" name="payee_name" id="payee_name" value="<?= e((string)$form['payee_name']) ?>" placeholder="مثال: صاحب العقار / الموظفين / شركة الكهرباء">
    </div>

    <div class="col-md-6">
      <label class="form-label">البيان</label>
      <input type="text" class="form-control" name="purpose" value="<?= e((string)$form['purpose']) ?>">
    </div>

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

    <div class="col-md-8">
      <label class="form-label">ملاحظات</label>
      <input type="text" class="form-control" name="notes" value="<?= e((string)$form['notes']) ?>">
    </div>
  </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(url($cash_payments_url ?? '/finance/cash-payments')) ?>">إلغاء</a>
  </div></div>
</form>

<script>
(function(){
  const q = document.getElementById('party_query');
  const box = document.getElementById('party_box');
  const hid = document.getElementById('party_id');
  const hidName = document.getElementById('party_name');
  const payee = document.getElementById('payee_name');
  if(!q || !box || !hid) return;

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

  q.addEventListener('input', async function(){
    const term = q.value.trim();
    hid.value = '0';
    hidName.value = '';
    if(term.length < 1){ hide(); return; }
    try{
      const res = await fetch("<?= e(url('/ajax/parties/search')) ?>?type=supplier&q=" + encodeURIComponent(term), {credentials:'same-origin'});
      if(!res.ok){ hide(); return; }
      const rows = await res.json();
      box.innerHTML = '';
      if(!rows || rows.length===0){ hide(); return; }
      rows.forEach(r=>{
        const a=document.createElement('a');
        a.href='#';
        a.className='list-group-item list-group-item-action';
        a.textContent = (r.name||'') + (r.code?(' - '+r.code):'') + (r.phone?(' - '+r.phone):'');
        a.addEventListener('click', (ev)=>{
          ev.preventDefault();
          hid.value = r.id;
          hidName.value = r.name || '';
          q.value = r.name || '';
          hide();
          if(payee && payee.value.trim()===''){ payee.value = r.name || ''; }
        });
        box.appendChild(a);
      });
      box.style.display='block';
    }catch(e){ hide(); }
  });

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

<script>
(function(){
  const source = document.getElementById('account_source_type');
  const paymentType = document.getElementById('payment_type');
  const cashboxWrap = document.getElementById('cashbox_wrap');
  const bankWrap = document.getElementById('bank_account_wrap');
  const partyWrap = document.getElementById('party_wrap');
  const expenseWrap = document.getElementById('expense_wrap');
  const expenseItem = document.getElementById('expense_item_id');
  const partyId = document.getElementById('party_id');
  const partyName = document.getElementById('party_name');
  const partyQuery = document.getElementById('party_query');
  const payee = document.getElementById('payee_name');

  function syncSource(){
    const v = (source && source.value) || 'cashbox';
    if (cashboxWrap) cashboxWrap.style.display = v === 'cashbox' ? 'block' : 'none';
    if (bankWrap) bankWrap.style.display = v === 'bank_account' ? 'block' : 'none';
  }

  function syncPaymentType(){
    const v = (paymentType && paymentType.value) || 'party';
    const isExpense = v === 'expense';
    if (partyWrap) partyWrap.style.display = isExpense ? 'none' : 'block';
    if (expenseWrap) expenseWrap.style.display = isExpense ? 'block' : 'none';
    if (isExpense) {
      if (partyId) partyId.value = '0';
      if (partyName) partyName.value = '';
      if (partyQuery) partyQuery.value = '';
    } else {
      if (expenseItem) expenseItem.value = '0';
    }
    syncSource();
  }

  if(source){ source.addEventListener('change', syncSource); syncSource(); }
  if(paymentType){ paymentType.addEventListener('change', syncPaymentType); syncPaymentType(); }
})();
</script>
