<?= $this->include('layout/header') ?>
<?php /** @var array $accounts */ /** @var string $title */ ?>
<?php $isArabic = (service('language')->getLocale() === 'ar'); ?>
<?php
  $lbl = [
    'description' => $isArabic ? 'الوصف' : 'Description',
    'date' => $isArabic ? 'التاريخ' : 'Date',
    'account' => $isArabic ? 'الحساب' : 'Account',
    'narration' => $isArabic ? 'البيان' : 'Narration',
    'debit' => $isArabic ? 'مدين' : 'Debit',
    'credit' => $isArabic ? 'دائن' : 'Credit',
    'totals' => $isArabic ? 'الإجمالي' : 'Totals',
    'noBalance' => $isArabic ? 'يجب تساوي المدين والدائن' : 'Debits must equal credits',
  ];
?>
<div class="container py-3" dir="<?= $isArabic ? 'rtl' : 'ltr' ?>">
  <div class="card shadow-sm">
    <div class="card-header d-flex justify-content-between align-items-center">
      <h5 class="mb-0"><?= esc($title) ?></h5>
    </div>
    <div class="card-body">
      <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger mb-3"><?= esc(session()->getFlashdata('error')) ?></div>
      <?php endif; ?>
      <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success mb-3"><?= esc(session()->getFlashdata('success')) ?></div>
      <?php endif; ?>

      <form method="post" action="/accounting/journal-vouchers/store" id="jvForm">
        <div class="row g-3 mb-3">
          <div class="col-md-7">
            <label class="form-label"><?= esc($lbl['description']) ?></label>
            <input type="text" name="description" class="form-control" />
          </div>
          <div class="col-md-3">
            <label class="form-label"><?= esc($lbl['date']) ?></label>
            <input type="date" name="date" class="form-control" value="<?= date('Y-m-d') ?>" />
          </div>
          <div class="col-md-2 d-flex align-items-end">
            <span class="badge bg-warning text-dark w-100" id="balanceMsg" style="display:none;"><?= esc($lbl['noBalance']) ?></span>
          </div>
        </div>

        <div class="table-responsive">
          <table class="table table-bordered" id="linesTable">
            <thead class="table-light">
              <tr>
                <th style="width:28%"><?= esc($lbl['account']) ?></th>
                <th><?= esc($lbl['narration']) ?></th>
                <th style="width:12%"><?= esc($lbl['debit']) ?></th>
                <th style="width:12%"><?= esc($lbl['credit']) ?></th>
              </tr>
            </thead>
            <tbody>
              <?php for ($i=0;$i<3;$i++): ?>
                <tr>
                  <td>
                    <select class="form-select" name="lines[<?= $i ?>][account_code]">
                      <option value=""><?= lang('App.choose') ?></option>
                      <?php foreach ($accounts as $a): ?>
                        <option value="<?= esc($a['code']) ?>"><?= esc($a['code']) ?> - <?= esc($a['display']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </td>
                  <td><input type="text" class="form-control" name="lines[<?= $i ?>][narration]" /></td>
                  <td><input type="number" step="0.01" class="form-control debit" name="lines[<?= $i ?>][debit]" /></td>
                  <td><input type="number" step="0.01" class="form-control credit" name="lines[<?= $i ?>][credit]" /></td>
                </tr>
              <?php endfor; ?>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="2" class="text-end"><strong><?= esc($lbl['totals']) ?></strong></td>
                <td><input type="text" class="form-control" id="totalDebit" readonly /></td>
                <td><input type="text" class="form-control" id="totalCredit" readonly /></td>
              </tr>
            </tfoot>
          </table>
        </div>

        <div class="d-flex gap-2">
          <button type="button" id="addRow" class="btn btn-secondary"><?= lang('App.add') ?> +</button>
          <button type="submit" id="saveBtn" class="btn btn-primary" disabled><?= lang('App.save') ?></button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(function(){
  const tbody = document.querySelector('#linesTable tbody');
  const addRowBtn = document.getElementById('addRow');
  const totalDebit = document.getElementById('totalDebit');
  const totalCredit = document.getElementById('totalCredit');
  const saveBtn = document.getElementById('saveBtn');
  const balanceMsg = document.getElementById('balanceMsg');

  function recalcTotals(){
    let d=0,c=0;
    document.querySelectorAll('#linesTable .debit').forEach(inp=>{ d += parseFloat(inp.value||0); });
    document.querySelectorAll('#linesTable .credit').forEach(inp=>{ c += parseFloat(inp.value||0); });
    totalDebit.value = d.toFixed(2);
    totalCredit.value = c.toFixed(2);
    const balanced = Math.abs(d - c) < 0.001 && d > 0 && c > 0;
    saveBtn.disabled = !balanced;
    balanceMsg.style.display = balanced ? 'none' : 'inline-block';
  }

  function bindRow(row){
    row.querySelectorAll('.debit, .credit').forEach(inp=>{
      inp.addEventListener('input', recalcTotals);
    });
  }

  document.querySelectorAll('#linesTable tbody tr').forEach(bindRow);

  addRowBtn.addEventListener('click', function(){
    const idx = tbody.querySelectorAll('tr').length;
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>
        <select class="form-select" name="lines[${idx}][account_code]">
          <option value=""><?= lang('App.choose') ?></option>
          <?php foreach ($accounts as $a): ?>
            <option value="<?= esc($a['code']) ?>"><?= esc($a['code']) ?> - <?= esc($a['display']) ?></option>
          <?php endforeach; ?>
        </select>
      </td>
      <td><input type="text" class="form-control" name="lines[${idx}][narration]" /></td>
      <td><input type="number" step="0.01" class="form-control debit" name="lines[${idx}][debit]" /></td>
      <td><input type="number" step="0.01" class="form-control credit" name="lines[${idx}][credit]" /></td>
    `;
    tbody.appendChild(row);
    bindRow(row);
  });

  recalcTotals();
})();
</script>
<?= $this->include('layout/footer') ?>