<?php
$isOut = (float)$inv['outstanding_amount'] > 0;
?>
<div class="d-flex flex-wrap gap-2 mb-3">
  <a class="btn btn-sm btn-light" href="<?= url('/invoice') ?>"><i class="bi bi-arrow-left me-1"></i>Kembali</a>
  <?php if (can('invoice','edit')): ?><a class="btn btn-sm btn-outline-primary" href="<?= url('/invoice/'.(int)$inv['id'].'/ubah') ?>"><i class="bi bi-pencil me-1"></i>Ubah</a><?php endif; ?>
  <?php if (can('pembayaran','create') && $isOut): ?><a class="btn btn-sm btn-success" href="<?= url('/pembayaran/tambah',['invoice_id'=>(int)$inv['id']]) ?>"><i class="bi bi-wallet2 me-1"></i>Catat Pembayaran</a><?php endif; ?>
  <?php if (can('penagihan','create') && $isOut): ?><a class="btn btn-sm btn-outline-secondary" href="<?= url('/penagihan/tambah',['invoice_id'=>(int)$inv['id']]) ?>"><i class="bi bi-telephone me-1"></i>Follow-up</a><?php endif; ?>
  <?php if (can('nota_kredit','create') && $isOut): ?><a class="btn btn-sm btn-outline-warning" href="<?= url('/nota-kredit/tambah',['invoice_id'=>(int)$inv['id']]) ?>"><i class="bi bi-file-earmark-minus me-1"></i>Nota Kredit</a><?php endif; ?>
  <?php if (can('invoice','print')): ?><a class="btn btn-sm btn-outline-dark" target="_blank" href="<?= url('/invoice/'.(int)$inv['id'].'/cetak') ?>"><i class="bi bi-printer me-1"></i>Cetak</a><?php endif; ?>
  <?php if (can('invoice','edit')): ?>
  <form method="post" action="<?= url('/invoice/'.(int)$inv['id'].'/hitung-ulang') ?>" class="d-inline"><?= csrf() ?>
    <button class="btn btn-sm btn-outline-secondary" data-konfirmasi="Hitung ulang seluruh nilai invoice ini dari data sumber?" data-konfirmasi-warna="primary"><i class="bi bi-arrow-clockwise me-1"></i>Hitung Ulang</button>
  </form>
  <?php endif; ?>
</div>

<?php if ($inv['doc_status'] !== 'active'): ?>
<div class="alert alert-warning d-flex align-items-center gap-2">
  <i class="bi bi-info-circle-fill"></i>
  <div>Invoice ini berstatus <strong><?= e(['cancelled'=>'Dibatalkan','replaced'=>'Diganti','revised'=>'Direvisi','written_off'=>'Dihapuskan'][$inv['doc_status']] ?? $inv['doc_status']) ?></strong>
  sehingga tidak dihitung sebagai piutang aktif maupun pendapatan.
  <?php if ($pengganti): ?> Digantikan oleh <a href="<?= url('/invoice/'.(int)$pengganti['id']) ?>"><strong><?= e($pengganti['invoice_no']) ?></strong></a>.<?php endif; ?>
  </div>
</div>
<?php endif; ?>
<?php if ($digantikan): ?>
<div class="alert alert-info d-flex align-items-center gap-2"><i class="bi bi-arrow-repeat"></i>
  <div>Invoice ini adalah pengganti dari <a href="<?= url('/invoice/'.(int)$digantikan['id']) ?>"><strong><?= e($digantikan['invoice_no']) ?></strong></a>.</div>
</div>
<?php endif; ?>
<?php $dq = arr($inv['dq_flags']); if ($dq): ?>
<div class="alert alert-warning">
  <strong><i class="bi bi-exclamation-triangle-fill me-1"></i>Catatan kualitas data:</strong>
  <ul class="mb-0 mt-1 small">
    <?php foreach ($dq as $f): ?><li><?= e(\App\Services\DataQualityService::FLAG_LABELS[$f] ?? $f) ?></li><?php endforeach; ?>
  </ul>
</div>
<?php endif; ?>

<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>Informasi Invoice</div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-6">
            <dl class="dl-grid">
              <dt>Nomor Invoice</dt><dd class="fw-bold"><?= e($inv['invoice_no']) ?></dd>
              <dt>Nomor Faktur Pajak</dt><dd class="font-monospace"><?= e($inv['tax_invoice_no'] ?: '-') ?></dd>
              <dt>Nomor SO</dt><dd><?= e($inv['so_no'] ?: '-') ?></dd>
              <dt>Customer</dt><dd><a href="<?= url('/kartu-piutang/'.(int)$inv['customer_id']) ?>"><?= e($inv['customer_name']) ?></a></dd>
              <dt>Outlet</dt><dd><?= e($inv['outlet_name'] ?: '-') ?></dd>
              <dt>NPWP Customer</dt><dd><?= e($inv['customer_npwp'] ?: '-') ?></dd>
              <dt>Area / Unit Bisnis</dt><dd><?= e($inv['area_name'] ?: '-') ?> / <?= e($inv['business_unit_name'] ?: '-') ?></dd>
              <dt>Sales</dt><dd><?= e($inv['salesperson_name'] ?: '-') ?></dd>
              <dt>Petugas Penagihan</dt><dd><?= e($inv['collection_officer_name'] ?: '(belum ditugaskan)') ?></dd>
            </dl>
          </div>
          <div class="col-md-6">
            <dl class="dl-grid">
              <dt>Tanggal Invoice</dt><dd><?= tgl($inv['invoice_date']) ?></dd>
              <dt>Tanggal WR</dt><dd><?= tgl($inv['wr_date']) ?></dd>
              <dt>Tanggal Kirim</dt><dd><?= tgl($inv['sent_date']) ?></dd>
              <dt>Jatuh Tempo</dt><dd class="fw-bold"><?= tgl($inv['due_date']) ?>
                <span class="text-body-secondary small">(<?= nf($inv['payment_term_days']) ?> hari dari
                <?= e(['invoice_date'=>'tgl invoice','sent_date'=>'tgl kirim','received_date'=>'tgl terima','tax_invoice_date'=>'tgl faktur pajak','wr_date'=>'tgl WR','manual'=>'manual'][$inv['due_date_basis']] ?? $inv['due_date_basis']) ?>)</span></dd>
              <dt>Kategori Pekerjaan</dt><dd><?= e($inv['job_category_name'] ?: '-') ?></dd>
              <dt>Jenis Pekerjaan</dt><dd><?= e($inv['job_type_name'] ?: '-') ?></dd>
              <dt>PMSC / By Case</dt><dd><?= e($inv['revenue_category_name'] ?: '-') ?></dd>
              <dt>Kanal Pengiriman</dt><dd><?= e($inv['send_channel'] ?: '-') ?><?= $inv['send_pic'] ? ' — ' . e($inv['send_pic']) : '' ?></dd>
              <dt>Sumber Data</dt><dd><?= e($inv['source'] === 'import' ? 'Import Excel' . ($inv['source_sheet'] ? ' (sheet ' . $inv['source_sheet'] . ')' : '') : 'Input Manual') ?></dd>
            </dl>
          </div>
        </div>
        <?php if ($inv['notes']): ?><hr><div class="small"><strong>Catatan:</strong> <?= nlbr($inv['notes']) ?></div><?php endif; ?>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-calculator me-1"></i>Rincian Perhitungan
        <span class="badge bg-info-subtle text-info-emphasis ms-1">Dihitung ulang oleh server</span></div>
      <div class="table-wrap">
        <table class="table table-sm mb-0">
          <tbody>
            <tr><td>Nominal Bruto (termasuk PPN <?= nf(setting('pajak.tarif_ppn',11),0) ?>%)</td><td class="num cell-strong"><?= rph($inv['gross_amount']) ?></td></tr>
            <tr class="text-body-secondary"><td class="ps-4">Dasar Pengenaan Pajak (DPP)</td><td class="num"><?= rph($inv['dpp_amount']) ?></td></tr>
            <tr class="text-body-secondary"><td class="ps-4">PPN</td><td class="num"><?= rph($inv['vat_amount']) ?></td></tr>
            <?php foreach ($deductions as $d): ?>
              <tr><td class="ps-4">(−) <?= e($d['name']) ?><?= (float)$d['rate'] > 0 ? ' <span class="text-body-secondary small">(' . nf($d['rate'],2) . '% dari DPP)</span>' : '' ?><?= $d['notes'] ? ' <span class="text-body-tertiary small">· ' . e($d['notes']) . '</span>' : '' ?></td>
                  <td class="num text-danger">(<?= e(rp((float)$d['amount'])) ?>)</td></tr>
            <?php endforeach; ?>
            <?php if (!$deductions): ?><tr class="text-body-secondary"><td class="ps-4">Tidak ada potongan</td><td class="num">-</td></tr><?php endif; ?>
            <tr class="table-light"><td class="fw-bold">Total Tagihan (Net)</td><td class="num fw-bold"><?= rph($inv['net_amount']) ?></td></tr>
            <tr><td>(−) Pembayaran Diterima (<?= nf($inv['payment_count']) ?> transaksi)</td><td class="num text-success"><?= rph($inv['paid_amount']) ?></td></tr>
            <?php if ((float)$inv['credit_note_amount'] != 0): ?>
              <tr><td>(−) Nota Kredit / Penyesuaian</td><td class="num text-success"><?= rph($inv['credit_note_amount']) ?></td></tr>
            <?php endif; ?>
            <tr class="table-warning"><td class="fw-bold">SALDO PIUTANG</td><td class="num fw-bold fs-6"><?= rph($inv['outstanding_amount']) ?></td></tr>
            <tr><td>Revenue Diakui</td><td class="num"><?= rph($inv['revenue_amount']) ?>
              <?= (int)$inv['is_revenue_counted'] === 0 ? ' <span class="badge bg-secondary-subtle text-secondary-emphasis">tidak dihitung</span>' : '' ?></td></tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-wallet2 me-1"></i>Riwayat Pembayaran (<?= count($payments) ?>)</div>
      <div class="table-wrap">
        <table class="table table-sm table-hover mb-0">
          <thead><tr><th>No. Pembayaran</th><th class="ctr">Tanggal</th><th>Metode</th><th>Bank</th><th>Referensi</th><th>Jenis</th><th class="num">Nilai</th><th class="ctr">Status</th></tr></thead>
          <tbody>
          <?php if (!$payments): ?><tr><td colspan="8" class="text-center text-body-secondary py-3">Belum ada pembayaran.</td></tr><?php endif; ?>
          <?php foreach ($payments as $pm): ?>
            <tr class="<?= $pm['status'] === 'reversed' ? 'text-decoration-line-through text-body-tertiary' : '' ?>">
              <td><a href="<?= url('/pembayaran/'.(int)$pm['id']) ?>"><?= e($pm['payment_no']) ?></a></td>
              <td class="ctr"><?= tgl($pm['payment_date']) ?></td>
              <td><?= e(\App\Services\PaymentService::METHODS[$pm['method']] ?? $pm['method']) ?></td>
              <td><?= e($pm['bank_name'] ?: '-') ?></td>
              <td class="small"><?= e($pm['reference_no'] ?: '-') ?></td>
              <td><?= badge(\App\Services\PaymentService::TYPES[$pm['payment_type']] ?? $pm['payment_type'], 'secondary') ?></td>
              <td class="num"><?= rph($pm['allocated_amount']) ?></td>
              <td class="ctr"><?= badge(['posted'=>'Diposting','draft'=>'Draf','reversed'=>'Dibalik'][$pm['status']] ?? $pm['status'], $pm['status']==='posted'?'success':($pm['status']==='reversed'?'dark':'warning')) ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

    <?php if ($revisions): ?>
    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-arrow-repeat me-1"></i>Revisi Invoice (RF)</div>
      <div class="table-wrap"><table class="table table-sm mb-0">
        <thead><tr><th>No. RF</th><th class="ctr">Tanggal</th><th>Invoice Lama</th><th>Invoice Baru</th><th>Jenis</th><th class="ctr">Status</th></tr></thead>
        <tbody><?php foreach ($revisions as $rv): ?>
          <tr><td><a href="<?= url('/revisi/'.(int)$rv['id']) ?>"><?= e($rv['rf_no']) ?></a></td>
            <td class="ctr"><?= tgl($rv['rf_date']) ?></td>
            <td><?= e($rv['old_invoice_no'] ?: '-') ?></td><td><?= e($rv['new_invoice_no'] ?: '-') ?></td>
            <td><?= e($rv['revision_type_name'] ?: '-') ?></td>
            <td class="ctr"><?= badge($rv['status'], $rv['status']==='approved'?'success':($rv['status']==='rejected'?'danger':'warning')) ?></td></tr>
        <?php endforeach; ?></tbody>
      </table></div>
    </div>
    <?php endif; ?>

    <?php if ($creditNotes): ?>
    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-file-earmark-minus me-1"></i>Nota Kredit & Penyesuaian</div>
      <div class="table-wrap"><table class="table table-sm mb-0">
        <thead><tr><th>No.</th><th class="ctr">Tanggal</th><th>Jenis</th><th class="num">Nilai</th><th class="ctr">Status</th><th>Alasan</th></tr></thead>
        <tbody><?php foreach ($creditNotes as $cn): ?>
          <tr><td><?= e($cn['cn_no']) ?></td><td class="ctr"><?= tgl($cn['cn_date']) ?></td>
            <td><?= e(\App\Controllers\CreditNoteController::TYPES[$cn['cn_type']] ?? $cn['cn_type']) ?></td>
            <td class="num"><?= rph($cn['amount']) ?></td>
            <td class="ctr"><?= badge($cn['status'], $cn['status']==='approved'?'success':($cn['status']==='rejected'?'danger':'warning')) ?></td>
            <td class="small"><?= e(truncate($cn['reason'],50)) ?></td></tr>
        <?php endforeach; ?></tbody>
      </table></div>
    </div>
    <?php endif; ?>
  </div>

  <div class="col-lg-4">
    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-info-circle me-1"></i>Status</div>
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <span class="text-body-secondary">Status Pembayaran</span><span><?= statusBadge($inv['payment_status_code']) ?></span></div>
        <div class="d-flex justify-content-between align-items-center mb-2">
          <span class="text-body-secondary">Status Dokumen</span><span><?= docStatusBadge($inv['doc_status']) ?></span></div>
        <div class="d-flex justify-content-between align-items-center mb-2">
          <span class="text-body-secondary">Umur Piutang</span>
          <span><?php $ag=$inv['aging_days']; echo $ag===null?'<span class="text-body-tertiary">-</span>':badge(nf($ag).' hari', agingColor((int)$ag)); ?></span></div>
        <div class="d-flex justify-content-between align-items-center mb-2">
          <span class="text-body-secondary">Hari Penagihan</span><span><?= $inv['collection_days']===null?'-':nf($inv['collection_days']).' hari' ?></span></div>
        <div class="d-flex justify-content-between align-items-center mb-2">
          <span class="text-body-secondary">Keterlambatan</span><span><?= $inv['days_late']===null?'-':nf($inv['days_late']).' hari' ?></span></div>
        <div class="d-flex justify-content-between align-items-center">
          <span class="text-body-secondary">Bayar Terakhir</span><span><?= tgl($inv['last_payment_date']) ?></span></div>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-paperclip me-1"></i>Lampiran (<?= count($attachments) ?>)</div>
      <div class="card-body">
        <?php if (can('lampiran','create')): ?>
        <form method="post" action="<?= url('/lampiran/unggah') ?>" enctype="multipart/form-data" class="mb-3" data-loading>
          <?= csrf() ?>
          <input type="hidden" name="entity_type" value="invoice">
          <input type="hidden" name="entity_id" value="<?= (int)$inv['id'] ?>">
          <div class="mb-2">
            <select class="form-select form-select-sm" name="attachment_type_id">
              <option value="">Pilih jenis dokumen…</option>
              <?php foreach ($attachmentTypes as $at): ?><option value="<?= (int)$at['id'] ?>"><?= e($at['name']) ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="input-group input-group-sm">
            <input type="file" class="form-control" name="berkas" required>
            <button class="btn btn-outline-primary" type="submit"><i class="bi bi-upload"></i></button>
          </div>
          <div class="form-text">Maks <?= nf(setting('keamanan.maks_ukuran_lampiran_mb',10),0) ?> MB. Berkas yang dapat dieksekusi ditolak otomatis.</div>
        </form>
        <?php endif; ?>
        <ul class="list-group list-group-flush small">
          <?php if (!$attachments): ?><li class="list-group-item text-body-secondary px-0">Belum ada lampiran.</li><?php endif; ?>
          <?php foreach ($attachments as $at): ?>
            <li class="list-group-item px-0 d-flex justify-content-between align-items-start gap-2">
              <div><a href="<?= url('/lampiran/'.(int)$at['id']) ?>"><?= e(truncate($at['file_name'],28)) ?></a>
                <div class="text-body-tertiary" style="font-size:11px"><?= e($at['type_name'] ?: 'Lainnya') ?> · <?= ukuranBerkas($at['file_size']) ?> · <?= e($at['uploaded_by_name'] ?: '') ?></div></div>
              <?php if (can('lampiran','delete')): ?>
              <form method="post" action="<?= url('/lampiran/'.(int)$at['id'].'/hapus') ?>"><?= csrf() ?>
                <button class="btn btn-sm btn-link text-danger p-0" data-konfirmasi="Hapus lampiran ini?"><i class="bi bi-trash"></i></button>
              </form>
              <?php endif; ?>
            </li>
          <?php endforeach; ?>
        </ul>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-header"><i class="bi bi-telephone me-1"></i>Follow-up Penagihan (<?= count($followups) ?>)</div>
      <div class="card-body">
        <?php if (!$followups): ?><p class="text-body-secondary small mb-0">Belum ada aktivitas penagihan.</p><?php endif; ?>
        <div class="timeline">
          <?php foreach (array_slice($followups,0,10) as $fu): ?>
            <div class="timeline-item">
              <div class="timeline-time"><?= tgl($fu['followup_date']) ?> · <?= e(\App\Services\CollectionService::METHODS[$fu['method']] ?? $fu['method']) ?></div>
              <div><?= $fu['status_name'] ? badge($fu['status_name'], $fu['status_color'] ?: 'secondary') : '' ?></div>
              <div class="small"><?= nlbr(truncate($fu['result'] ?: '-',160)) ?></div>
              <div class="text-body-tertiary" style="font-size:11px"><?= e($fu['officer_name'] ?: $fu['created_by_name'] ?: '') ?></div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>

    <?php if (can('audit','view') && $audit): ?>
    <div class="card">
      <div class="card-header"><i class="bi bi-clock-history me-1"></i>Riwayat Perubahan</div>
      <div class="card-body">
        <div class="timeline">
          <?php foreach (array_slice($audit,0,12) as $a): ?>
            <div class="timeline-item">
              <div class="timeline-time"><?= tglWaktu($a['created_at']) ?></div>
              <div class="small"><strong><?= e(\App\Core\Audit::actionLabel($a['action'])) ?></strong> — <?= e($a['user_name'] ?: 'Sistem') ?></div>
              <div class="small text-body-secondary"><?= e(truncate($a['description'],110)) ?></div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>
  </div>
</div>
