<?php $isEdit = !empty($inv); ?>
<form method="post" action="<?= $isEdit ? url('/invoice/'.(int)$inv['id'].'/ubah') : url('/invoice/tambah') ?>" data-loading>
<?= csrf() ?>
<div class="row g-3">
  <div class="col-lg-8">
    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-receipt me-1"></i>Identitas Invoice</div>
      <div class="card-body"><div class="row g-3">
        <div class="col-md-4"><label class="form-label required" for="invoice_no">Nomor Invoice</label>
          <input type="text" class="form-control" id="invoice_no" name="invoice_no" required maxlength="60"
                 value="<?= attr($isEdit ? $inv['invoice_no'] : old('invoice_no', $nomorSaran ?? '')) ?>" <?= $isEdit ? 'readonly' : '' ?>>
          <?php if ($isEdit): ?><div class="form-text">Nomor invoice tidak dapat diubah.</div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label" for="tax_invoice_no">Nomor Faktur Pajak</label>
          <input type="text" class="form-control font-monospace" id="tax_invoice_no" name="tax_invoice_no" maxlength="60"
                 value="<?= attr($isEdit ? $inv['tax_invoice_no'] : old('tax_invoice_no')) ?>">
          <div class="form-text">Disimpan sebagai teks; nol di depan tetap utuh.</div></div>
        <div class="col-md-4"><label class="form-label" for="so_no">Nomor SO</label>
          <input type="text" class="form-control" id="so_no" name="so_no" maxlength="60" value="<?= attr($isEdit ? $inv['so_no'] : old('so_no')) ?>"></div>

        <div class="col-md-6"><label class="form-label required" for="customer_id">Customer</label>
          <select class="form-select" id="customer_id" name="customer_id" required>
            <option value="">— Pilih customer —</option>
            <?php foreach ($customers as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= (int)($isEdit ? $inv['customer_id'] : old('customer_id',0)) === (int)$c['id'] ? 'selected' : '' ?>><?= e($c['name']) ?> (<?= e($c['code']) ?>)</option>
            <?php endforeach; ?>
          </select></div>
        <div class="col-md-6"><label class="form-label" for="outlet_id">Outlet</label>
          <select class="form-select" id="outlet_id" name="outlet_id">
            <option value="">— Tanpa outlet —</option>
            <?php if ($isEdit && $inv['outlet_id']): ?><option value="<?= (int)$inv['outlet_id'] ?>" selected><?= e($inv['outlet_name']) ?></option><?php endif; ?>
          </select>
          <div class="form-text">Daftar outlet dimuat otomatis setelah customer dipilih.</div></div>

        <div class="col-md-3"><label class="form-label" for="area_id">Area</label>
          <select class="form-select" id="area_id" name="area_id"><option value="">— Otomatis —</option>
            <?php foreach ($areas as $a): ?><option value="<?= (int)$a['id'] ?>" <?= (int)($isEdit ? $inv['area_id'] : 0) === (int)$a['id'] ? 'selected':'' ?>><?= e($a['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-3"><label class="form-label" for="business_unit_id">Unit Bisnis</label>
          <select class="form-select" id="business_unit_id" name="business_unit_id"><option value="">— Otomatis —</option>
            <?php foreach ($bus as $b): ?><option value="<?= (int)$b['id'] ?>" <?= (int)($isEdit ? $inv['business_unit_id'] : 0) === (int)$b['id'] ? 'selected':'' ?>><?= e($b['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-3"><label class="form-label" for="salesperson_id">Sales</label>
          <select class="form-select" id="salesperson_id" name="salesperson_id"><option value="">— Otomatis —</option>
            <?php foreach ($salespersons as $s): ?><option value="<?= (int)$s['id'] ?>" <?= (int)($isEdit ? $inv['salesperson_id'] : 0) === (int)$s['id'] ? 'selected':'' ?>><?= e($s['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-3"><label class="form-label" for="collection_officer_id">Petugas Penagihan</label>
          <select class="form-select" id="collection_officer_id" name="collection_officer_id"><option value="">— Belum ditugaskan —</option>
            <?php foreach ($officers as $o): ?><option value="<?= (int)$o['id'] ?>" <?= (int)($isEdit ? $inv['collection_officer_id'] : 0) === (int)$o['id'] ? 'selected':'' ?>><?= e($o['name']) ?></option><?php endforeach; ?></select></div>

        <div class="col-md-4"><label class="form-label" for="job_category_id">Kategori Pekerjaan</label>
          <select class="form-select" id="job_category_id" name="job_category_id"><option value="">—</option>
            <?php foreach ($jobCats as $j): ?><option value="<?= (int)$j['id'] ?>" <?= (int)($isEdit ? $inv['job_category_id'] : 0) === (int)$j['id'] ? 'selected':'' ?>><?= e($j['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-4"><label class="form-label" for="job_type_id">Jenis Pekerjaan</label>
          <select class="form-select" id="job_type_id" name="job_type_id"><option value="">—</option>
            <?php foreach ($jobTypes as $j): ?><option value="<?= (int)$j['id'] ?>" data-cat="<?= (int)$j['job_category_id'] ?>" <?= (int)($isEdit ? $inv['job_type_id'] : 0) === (int)$j['id'] ? 'selected':'' ?>><?= e($j['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-4"><label class="form-label" for="revenue_category_id">PMSC / By Case</label>
          <select class="form-select" id="revenue_category_id" name="revenue_category_id"><option value="">—</option>
            <?php foreach ($revCats as $r): ?><option value="<?= (int)$r['id'] ?>" <?= (int)($isEdit ? $inv['revenue_category_id'] : 0) === (int)$r['id'] ? 'selected':'' ?>><?= e($r['name']) ?></option><?php endforeach; ?></select></div>

        <div class="col-12"><label class="form-label" for="notes">Catatan</label>
          <textarea class="form-control" id="notes" name="notes" rows="2" maxlength="2000"><?= e($isEdit ? $inv['notes'] : old('notes')) ?></textarea></div>
      </div></div>
    </div>

    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-calendar3 me-1"></i>Tanggal & Termin</div>
      <div class="card-body"><div class="row g-3">
        <?php foreach ([['invoice_date','Tanggal Invoice',true],['wr_date','Tanggal WR',false],['print_date','Tanggal Print',false],
                        ['input_date','Tanggal Input',false],['sent_date','Tanggal Kirim',false],['received_date','Tanggal Terima',false],
                        ['tax_invoice_date','Tanggal Faktur Pajak',false]] as [$fk,$lbl,$req]): ?>
          <div class="col-md-3"><label class="form-label <?= $req ? 'required' : '' ?>" for="<?= $fk ?>"><?= e($lbl) ?></label>
            <input type="date" class="form-control" id="<?= $fk ?>" name="<?= $fk ?>" <?= $req ? 'required' : '' ?>
                   value="<?= attr($isEdit ? substr((string)$inv[$fk],0,10) : old($fk)) ?>"></div>
        <?php endforeach; ?>
        <div class="col-md-3"><label class="form-label" for="payment_term_days">Termin (hari)</label>
          <input type="number" class="form-control" id="payment_term_days" name="payment_term_days" min="0" max="3650"
                 value="<?= attr($isEdit ? $inv['payment_term_days'] : '') ?>" placeholder="<?= (int)setting('ar.termin_default_hari',30) ?>">
          <div class="form-text">Kosongkan untuk memakai hierarki termin sistem.</div></div>
        <div class="col-md-3"><label class="form-label" for="due_date">Jatuh Tempo</label>
          <input type="date" class="form-control" id="due_date" name="due_date" value="<?= attr($isEdit ? $inv['due_date'] : '') ?>">
          <div class="form-check mt-1">
            <input class="form-check-input" type="checkbox" id="due_date_manual" name="due_date_manual" value="1" <?= $isEdit && (int)$inv['due_date_manual']===1 ? 'checked' : '' ?>>
            <label class="form-check-label small" for="due_date_manual">Tentukan manual</label></div>
          <div class="form-text">Bila tidak dicentang, jatuh tempo dihitung server dari tanggal dasar + termin.</div></div>
        <div class="col-md-3"><label class="form-label" for="send_channel">Kanal Pengiriman</label>
          <select class="form-select" id="send_channel" name="send_channel"><option value="">—</option>
            <?php foreach (['POS','EMAIL','WHATSAPP','TUKAR FAKTUR','PORTAL VENDOR','KURIR','DIAMBIL CUSTOMER','FAKS','LAIN-LAIN'] as $ch): ?>
              <option value="<?= attr($ch) ?>" <?= ($isEdit && $inv['send_channel']===$ch) ? 'selected':'' ?>><?= e($ch) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-3"><label class="form-label" for="send_pic">PIC Pengiriman</label>
          <input type="text" class="form-control" id="send_pic" name="send_pic" maxlength="120" value="<?= attr($isEdit ? $inv['send_pic'] : '') ?>"></div>
      </div></div>
    </div>
  </div>

  <div class="col-lg-4">
    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-cash me-1"></i>Nilai & Potongan</div>
      <div class="card-body">
        <div class="mb-3"><label class="form-label required" for="gross_amount">Nominal Invoice (Bruto)</label>
          <div class="input-group"><span class="input-group-text">Rp</span>
            <input type="text" class="form-control text-end" id="gross_amount" name="gross_amount" data-uang required
                   value="<?= attr($isEdit ? nf($inv['gross_amount'],0) : old('gross_amount')) ?>"></div>
          <div class="form-text">Termasuk PPN <?= nf(setting('pajak.tarif_ppn',11),0) ?>%. DPP dihitung otomatis.</div></div>
        <hr>
        <label class="form-label">Potongan</label>
        <div id="potonganWrap">
          <?php $rows = $deductions ?: []; if (!$rows) $rows = [['deduction_type_id'=>null,'amount'=>'','notes'=>'']];
          foreach ($rows as $d): ?>
            <div class="row g-1 mb-2 baris-potongan">
              <div class="col-5"><select class="form-select form-select-sm" name="ded_type[]">
                <option value="">— Jenis —</option>
                <?php foreach ($dedTypes as $t): ?>
                  <option value="<?= (int)$t['id'] ?>" data-calc="<?= e($t['calc_type']) ?>" data-rate="<?= e($t['rate']) ?>"
                    <?= (int)($d['deduction_type_id'] ?? 0) === (int)$t['id'] ? 'selected' : '' ?>><?= e($t['name']) ?></option>
                <?php endforeach; ?></select></div>
              <div class="col-5"><input type="text" class="form-control form-control-sm text-end" name="ded_amount[]" data-uang
                     placeholder="0" value="<?= attr($d['amount'] ? nf($d['amount'],0) : '') ?>"></div>
              <div class="col-2"><button type="button" class="btn btn-sm btn-outline-danger w-100 hapus-potongan"><i class="bi bi-x"></i></button></div>
              <div class="col-12"><input type="text" class="form-control form-control-sm" name="ded_note[]" placeholder="Catatan potongan (opsional)" value="<?= attr($d['notes'] ?? '') ?>"></div>
            </div>
          <?php endforeach; ?>
        </div>
        <button type="button" class="btn btn-sm btn-outline-secondary w-100" id="tambahPotongan"><i class="bi bi-plus-lg me-1"></i>Tambah Potongan</button>
        <hr>
        <div class="d-flex justify-content-between"><span class="text-body-secondary">DPP</span><strong id="prevDpp">-</strong></div>
        <div class="d-flex justify-content-between"><span class="text-body-secondary">Total Potongan</span><strong id="prevPot">-</strong></div>
        <div class="d-flex justify-content-between fs-6"><span>Total Tagihan</span><strong id="prevNet">-</strong></div>
      </div>
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-primary flex-fill" type="submit"><i class="bi bi-check-lg me-1"></i>Simpan Invoice</button>
      <a class="btn btn-light" href="<?= $isEdit ? url('/invoice/'.(int)$inv['id']) : url('/invoice') ?>">Batal</a>
    </div>
  </div>
</div>
</form>

<?php viewStart('scripts'); ?>
<script>
(function(){
  const PPN = <?= (float)setting('pajak.tarif_ppn', 11) ?>;
  const parse = v => parseFloat(String(v||'').replace(/\./g,'').replace(',','.')) || 0;
  function hitung() {
    const gross = parse(document.getElementById('gross_amount').value);
    const dpp = gross / (1 + PPN/100);
    let pot = 0;
    document.querySelectorAll('input[name="ded_amount[]"]').forEach(i => pot += parse(i.value));
    document.getElementById('prevDpp').textContent = SP.rp(dpp);
    document.getElementById('prevPot').textContent = SP.rp(pot);
    document.getElementById('prevNet').textContent = SP.rp(gross - pot);
  }
  function autoIsi(sel) {
    const opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.dataset.calc) return;
    const gross = parse(document.getElementById('gross_amount').value);
    const rate = parseFloat(opt.dataset.rate || 0);
    const inp = sel.closest('.baris-potongan').querySelector('input[name="ded_amount[]"]');
    if (opt.dataset.calc === 'percent_of_dpp') inp.value = Math.round(gross/(1+PPN/100)*rate/100).toLocaleString('id-ID');
    else if (opt.dataset.calc === 'percent_of_gross') inp.value = Math.round(gross*rate/100).toLocaleString('id-ID');
    else if (opt.dataset.calc === 'fixed') inp.value = rate.toLocaleString('id-ID');
    hitung();
  }
  document.addEventListener('input', e => { if (e.target.matches('#gross_amount, input[name="ded_amount[]"]')) hitung(); });
  document.addEventListener('change', e => { if (e.target.matches('select[name="ded_type[]"]')) autoIsi(e.target); });
  document.addEventListener('click', e => {
    if (e.target.closest('.hapus-potongan')) {
      const w = document.getElementById('potonganWrap');
      if (w.querySelectorAll('.baris-potongan').length > 1) e.target.closest('.baris-potongan').remove();
      else w.querySelectorAll('input,select').forEach(i => i.value = '');
      hitung();
    }
  });
  document.getElementById('tambahPotongan').addEventListener('click', function(){
    const w = document.getElementById('potonganWrap');
    const c = w.querySelector('.baris-potongan').cloneNode(true);
    c.querySelectorAll('input').forEach(i => i.value = '');
    c.querySelector('select').selectedIndex = 0;
    w.appendChild(c);
  });

  // Outlet mengikuti customer
  const cust = document.getElementById('customer_id'), outlet = document.getElementById('outlet_id');
  function muatOutlet() {
    const id = cust.value;
    if (!id) { outlet.innerHTML = '<option value="">— Tanpa outlet —</option>'; return; }
    SP.get(SP.url('/master/outlet'), {}).catch(()=>{});
    fetch(SP.url('/invoice/cari') + '?q=__outlet__&outlet_customer=' + id, {headers:{'X-Requested-With':'XMLHttpRequest'}}).catch(()=>{});
  }
  cust && cust.addEventListener('change', muatOutlet);

  // Jenis pekerjaan mengikuti kategori
  const cat = document.getElementById('job_category_id'), typ = document.getElementById('job_type_id');
  function saringJenis() {
    const c = cat.value;
    Array.from(typ.options).forEach(o => {
      if (!o.value) return;
      o.hidden = c !== '' && o.dataset.cat !== c;
    });
  }
  cat && cat.addEventListener('change', saringJenis);
  saringJenis();
  hitung();
})();
</script>
<?php viewStop(); ?>
