<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>

<style>
.page-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:28px; flex-wrap:wrap; gap:12px; }
.page-title   { font-size:1.4rem; font-weight:700; color:var(--text-main); display:flex; align-items:center; gap:10px; }
.page-title i { color:var(--accent); }
.page-subtitle{ font-size:.8rem; color:var(--text-muted); margin-top:2px; }

.stat-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:16px; margin-bottom:28px; }
.stat-card { background:#fff; border:1px solid var(--border); border-radius:14px; padding:20px; position:relative; overflow:hidden; transition:border-color .2s, transform .2s; box-shadow:0 1px 3px rgba(0,0,0,.05); text-align:center; }
.stat-card:hover { border-color:rgba(59,130,246,.3); transform:translateY(-2px); }
.stat-card .stat-icon { width:40px; height:40px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:1.1rem; margin-bottom:14px; }
.stat-card .stat-value { font-size:2.2rem; font-weight:800; color:var(--accent); line-height:1; margin-bottom:8px; margin-top:8px; }
.stat-card .stat-label { font-size:.8rem; color:var(--text-muted); text-transform:uppercase; letter-spacing:.05em; font-weight:600; }

.table-card { background:#fff; border:1px solid var(--border); border-radius:14px; overflow:hidden; margin-bottom:20px; box-shadow:0 1px 3px rgba(0,0,0,.05); }
.table-card-header { padding:16px 20px; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; }
.table-card-title { font-size:.9rem; font-weight:600; color:var(--text-main); }
.table-responsive { overflow-x:auto; }
.sim-table { width:100%; border-collapse:collapse; font-size:.83rem; }
.sim-table thead tr { background:#f8fafc; }
.sim-table thead th { padding:11px 16px; text-align:left; color:var(--text-muted); font-weight:600; font-size:.72rem; text-transform:uppercase; letter-spacing:.06em; border-bottom:1px solid var(--border); white-space:nowrap; }
.sim-table tbody tr { border-bottom:1px solid var(--border); transition:background .15s; }
.sim-table tbody tr:last-child { border-bottom:none; }
.sim-table tbody tr:hover { background:#f8fafc; }
.sim-table tbody td { padding:11px 16px; color:#334155; vertical-align:middle; }

.badge-sim { display:inline-flex; align-items:center; gap:4px; font-size:.7rem; font-weight:600; padding:3px 9px; border-radius:20px; }
.badge-success { background:rgba(16,185,129,.12); color:#059669; border:1px solid rgba(16,185,129,.2); }
.badge-danger  { background:rgba(239,68,68,.12);  color:#dc2626; border:1px solid rgba(239,68,68,.2); }

.filter-bar { display:flex; gap:8px; flex-wrap:wrap; }
.sim-select, .sim-input { width:100%; background:#fff; border:1px solid var(--border); color:var(--text-main); border-radius:8px; padding:8px 12px; font-size:.8rem; outline:none; transition:border-color .15s; margin-bottom:12px; }
.sim-select:focus, .sim-input:focus { border-color:var(--accent); box-shadow:0 0 0 3px rgba(59,130,246,.1); }
.sim-select:disabled, .sim-input[readonly] { background:#f8fafc; color:var(--text-muted); cursor:not-allowed; }
.sim-select option { background:#fff; }

.btn-accent { background:linear-gradient(90deg, #3b82f6, #6366f1); border:none; color:#fff; border-radius:8px; padding:8px 14px; font-size:.85rem; font-weight:600; cursor:pointer; transition:opacity .15s; display:inline-flex; align-items:center; justify-content:center; gap:6px; width:100%; }
.btn-accent:disabled { opacity:.5; cursor:not-allowed; }
.btn-accent:hover:not(:disabled) { opacity:.85; }

.form-label { font-size:.8rem; color:var(--text-muted); font-weight:500; margin-bottom:6px; display:block; }
.alert-sim { padding:12px 16px; border-radius:8px; margin-bottom:20px; display:flex; align-items:center; gap:10px; font-size:.85rem; font-weight:500; }
.alert-sim-success { background:rgba(16,185,129,.08); border:1px solid rgba(16,185,129,.25); color:#059669; }
.alert-sim-danger  { background:rgba(239,68,68,.08);  border:1px solid rgba(239,68,68,.25);  color:#dc2626; }
.grid-2 { display:grid; grid-template-columns:1fr 2fr; gap:20px; align-items:start; }
@media(max-width: 900px) { .grid-2 { grid-template-columns:1fr; } }
</style>

<!-- Page Header -->
<div class="page-header">
    <div>
        <div class="page-title"><i class="bi bi-wallet2" style="color:#4f8ef7"></i> Kas Ledger</div>
        <div class="page-subtitle">Sistem Pencatatan Kas Keluar Operasional</div>
    </div>
</div>

<?php if(session()->getFlashdata('success')): ?>
  <div class="alert-sim alert-sim-success"><i class="bi bi-check-circle"></i> <?= session()->getFlashdata('success') ?></div>
<?php endif; ?>
<?php if(session()->getFlashdata('error')): ?>
  <div class="alert-sim alert-sim-danger"><i class="bi bi-exclamation-triangle"></i> <?= session()->getFlashdata('error') ?></div>
<?php endif; ?>

<!-- Stat Card Khusus Saldo -->
<div class="stat-grid">
    <div class="stat-card" style="text-align: center;">
        <div class="stat-label">TOTAL SALDO BERJALAN (LIVE)</div>
        <div class="stat-value" style="color: #facc15; font-size: 2.2rem; margin-top: 5px;">Rp <?= number_format($saldo, 2, ',', '.') ?></div>
    </div>
</div>

<div class="grid-2">
  <!-- FORM INPUT -->
  <div class="table-card" style="border-top: 4px solid #7c5cfc;">
    <div class="table-card-header">
        <span class="table-card-title"><i class="bi bi-pencil-square" style="color:var(--accent);margin-right:6px"></i>Jurnal Transaksi Baru</span>
    </div>

    <div style="padding: 20px;">
        <form action="<?= base_url('/finance/store') ?>" method="post" id="formKas">

          <input type="hidden" name="tipe_transaksi" id="tipe_transaksi" value="Pengeluaran">

          <span class="form-label">Tanggal Transaksi</span>
          <input type="date" name="tanggal" class="sim-input" required value="<?= date('Y-m-d') ?>">

          <span class="form-label">Kategori (Klasifikasi Ledger)</span>
          <select name="kategori" id="kategori" class="sim-select" required>
            <option value="" selected disabled>-- Pilih Kategori Pengeluaran --</option>
            <option value="Listrik">Bayar Listrik / Air</option>
            <option value="Maintenance Mesin">Bayar Servis Mesin</option>
            <option value="Biaya Gaji / Upah Karyawan">Bayar Gaji Karyawan (Interkoneksi Sistem)</option>
            <option value="Bahan Baku">Belanja Bahan Baku (Rekan Tim Inventory)</option>
            <option value="Operasional Lainnya">Operasional Harian Lainnya</option>
          </select>

          <!-- BLOK DINAMIS UNTUK GAJI -->
          <div id="blok_gaji" style="display: none; background: rgba(79, 142, 247, 0.05); padding: 15px; border-radius: 8px; border: 1px dashed rgba(79,142,247,0.4); margin-bottom: 15px;">
            <span class="form-label" style="color: #4f8ef7;"><i class="bi bi-person-lines-fill"></i> Pilih Tagihan Slip Gaji Aktif</span>
            <select name="id_penggajian" id="id_penggajian" class="sim-select" style="margin-bottom:8px">
              <option value="" selected disabled>-- Pilih Karyawan --</option>
              <?php foreach ($unpaidGaji as $g): ?>
                <option value="<?= $g['id_penggajian'] ?>" data-nominal="<?= $g['total_gaji_penggajian'] ?>">
                  [<?= $g['periode_bulan_penggajian'] ?>] <?= $g['nama_karyawan'] ?> - Rp <?= number_format($g['total_gaji_penggajian'], 0, ',', '.') ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div style="font-size:0.7rem; color:var(--text-muted);"><i class="bi bi-info-circle"></i> Membayar lewat form ini akan otomatis melunasi tagihan HRD.</div>
          </div>

          <!-- BLOK STANDAR -->
          <div id="blok_manual">
            <span class="form-label">Keterangan / Catatan Transaksi <span style="color:#f87171">*</span></span>
            <input type="text" name="keterangan" id="keterangan" class="sim-input" placeholder="Contoh: Bayar listrik pabrik">

            <span class="form-label">Nominal Pembayaran (IDR) <span style="color:#f87171">*</span></span>
            <input type="number" name="nominal" id="nominal" class="sim-input" placeholder="Contoh: 1500000" min="0">
          </div>

          <button type="submit" id="btnSimpan" class="btn-accent" style="margin-top:5px" disabled><i class="bi bi-save"></i> Eksekusi ke Ledger</button>
        </form>
    </div>
  </div>

  <!-- TABEL LAPORAN PENGELUARAN -->
  <div class="table-card">
    <div class="table-card-header">
        <span class="table-card-title"><i class="bi bi-arrow-up-right-circle" style="color:#dc2626;margin-right:6px"></i>Laporan Pengeluaran</span>
    </div>
    <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
      <table class="sim-table">
        <thead>
          <tr>
            <th>Tanggal</th>
            <th>Kategori</th>
            <th>Keterangan</th>
            <th style="text-align: right;">Nominal</th>
          </tr>
        </thead>
        <tbody>
          <?php 
          $totalPengeluaran = 0;
          foreach($transaksi as $t): 
            if($t['tipe_transaksi_kas'] !== 'Pengeluaran') continue;
            $totalPengeluaran += $t['nominal_transaksi_kas'];
          ?>
          <tr>
            <td style="white-space: nowrap; color: var(--text-muted)"><?= date('d M Y', strtotime($t['tanggal_transaksi_kas'])) ?></td>
            <td>
              <div style="font-weight: 600; color: var(--text-main); font-size: 0.8rem;"><?= $t['kategori_transaksi_kas'] ?></div>
            </td>
            <td>
              <div style="font-size: 0.72rem; color: var(--text-muted);"><?= $t['keterangan_transaksi_kas'] ?></div>
            </td>
            <td style="text-align: right; font-weight: bold; font-family: monospace; color: #dc2626;">
              Rp <?= number_format($t['nominal_transaksi_kas'], 0, ',', '.') ?>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
        <?php if($totalPengeluaran > 0): ?>
        <tfoot>
          <tr style="background:#fef2f2; border-top: 2px solid #fecaca;">
            <td colspan="3" style="padding:11px 16px; font-weight:700; font-size:.8rem; color:#dc2626;">TOTAL PENGELUARAN</td>
            <td style="padding:11px 16px; text-align:right; font-weight:800; font-family:monospace; color:#dc2626;">
              Rp <?= number_format($totalPengeluaran, 0, ',', '.') ?>
            </td>
          </tr>
        </tfoot>
        <?php endif; ?>
      </table>
      <?php 
      $adaPengeluaran = false;
      foreach($transaksi as $t) { if($t['tipe_transaksi_kas'] === 'Pengeluaran') { $adaPengeluaran = true; break; } }
      if(!$adaPengeluaran): ?>
         <div style="text-align: center; color: var(--text-muted); padding: 2rem; font-size: 0.8rem;">Belum ada catatan pengeluaran.</div>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
  const elKategori = document.getElementById('kategori');
  const elBlokGaji = document.getElementById('blok_gaji');
  const elBlokManual = document.getElementById('blok_manual');
  const elIdPenggajian = document.getElementById('id_penggajian');
  const elNominal = document.getElementById('nominal');
  const elKeterangan = document.getElementById('keterangan');
  const elBtn = document.getElementById('btnSimpan');

  elKategori.addEventListener('change', function() {
    elBtn.disabled = false;

    if(this.value === 'Biaya Gaji / Upah Karyawan') {
      elBlokGaji.style.display = 'block';
      elBlokManual.style.display = 'block';
      elNominal.readOnly = true;
      elKeterangan.readOnly = true;
      elIdPenggajian.required = true;
      elNominal.required = false;
      elNominal.value = '';
      elKeterangan.value = 'Auto-synchronized by HRD Module System';
    } else {
      elBlokGaji.style.display = 'none';
      elBlokManual.style.display = 'block';
      elNominal.readOnly = false;
      elKeterangan.readOnly = false;
      elIdPenggajian.required = false;
      elNominal.required = true;

      if(this.value === 'Bahan Baku') {
        elKeterangan.value = '[INV] Pembelian: ';
      } else {
        elKeterangan.value = '';
      }
    }
  });

  elIdPenggajian.addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    const nom = selectedOption.getAttribute('data-nominal');
    if(nom) {
      elNominal.value = nom;
    }
  });
</script>
<?= $this->endSection() ?>
