<?php
$bulan_nama = ['','Januari','Februari','Maret','April','Mei','Juni',
               'Juli','Agustus','September','Oktober','November','Desember'];
$total_terbayar = $iuran->total_terbayar ?: 0;
$sisa           = max(0, $iuran->nominal - $total_terbayar);
$persen         = ($iuran->nominal > 0) ? round(($total_terbayar / $iuran->nominal) * 100) : 0;
?>

<div class="container-fluid">
  <form action="<?php echo base_url('iuran/bayar/' . $iuran->id); ?>" method="post" enctype="multipart/form-data">
    <div class="row g-4">

      <!-- ═══ KOLOM KIRI: Detail Tagihan ═══ -->
      <div class="col-md-4">
        <div class="card border-0 shadow-sm h-100" style="border-radius:15px">
          <div class="card-body px-4 py-4">

            <div class="d-flex align-items-center gap-2 mb-4">
              <div class="rounded-circle bg-success bg-opacity-10 d-flex align-items-center justify-content-center" style="width:36px;height:36px">
                <i class="bi bi-receipt text-success"></i>
              </div>
              <div class="fw-bold small text-uppercase" style="letter-spacing:.5px">Detail Tagihan</div>
            </div>

            <div class="mb-3">
              <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.5px">Nama Warga</div>
              <div class="fw-semibold"><?php echo $iuran->nama_lengkap; ?></div>
            </div>
            <div class="mb-3">
              <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.5px">NIK</div>
              <div class="fw-semibold"><?php echo $iuran->nik; ?></div>
            </div>
            <div class="mb-3">
              <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.5px">Jenis Iuran</div>
              <div class="fw-semibold"><?php echo $iuran->nama_iuran; ?></div>
            </div>
            <div class="mb-3">
              <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.5px">Periode</div>
              <div class="fw-semibold"><?php echo $bulan_nama[(int)$iuran->periode_bulan] . ' ' . $iuran->periode_tahun; ?></div>
            </div>
            <div class="mb-3">
              <div class="text-muted" style="font-size:11px;text-transform:uppercase;letter-spacing:.5px">Nominal Tagihan</div>
              <div class="fw-bold fs-4 text-success">Rp <?php echo number_format($iuran->nominal,0,',','.'); ?></div>
            </div>

            <?php if($total_terbayar > 0): ?>
            <hr class="my-3">
            <div class="mb-1 d-flex justify-content-between small">
              <span class="text-success">Terbayar: <strong>Rp <?php echo number_format($total_terbayar,0,',','.'); ?></strong></span>
              <span class="text-danger">Sisa: <strong>Rp <?php echo number_format($sisa,0,',','.'); ?></strong></span>
            </div>
            <div class="progress mb-1" style="height:8px;border-radius:10px">
              <div class="progress-bar bg-success" style="width:<?php echo $persen; ?>%;border-radius:10px"></div>
            </div>
            <div class="text-center text-muted small"><?php echo $persen; ?>% · <?php echo $iuran->jumlah_cicilan ?? 0; ?> cicilan</div>
            <?php endif; ?>

            <?php if(($iuran->jumlah_cicilan ?? 0) > 0): ?>
            <a href="<?php echo base_url('iuran/history_cicilan/' . $iuran->id); ?>"
               class="btn btn-sm btn-outline-secondary w-100 mt-3">
              <i class="bi bi-clock-history me-1"></i>History Cicilan
            </a>
            <?php endif; ?>

          </div>
        </div>
      </div>

      <!-- ═══ KOLOM KANAN: Form Bayar ═══ -->
      <div class="col-md-8">
        <div class="card border-0 shadow-sm" style="border-radius:15px">
          <div class="card-header bg-white border-0 pt-4 px-4 pb-3">
            <div class="d-flex align-items-center gap-2 mb-3">
              <div class="rounded-circle bg-success bg-opacity-10 d-flex align-items-center justify-content-center" style="width:36px;height:36px">
                <i class="bi bi-cash-coin text-success"></i>
              </div>
              <div>
                <div class="fw-bold">DATA PEMBAYARAN</div>
                <div class="text-muted small">Input pembayaran langsung oleh admin</div>
              </div>
            </div>

            <!-- Toggle Mode -->
            <div class="d-flex gap-2">
              <input type="radio" class="btn-check" name="mode_bayar" id="mode_lunas" value="lunas" checked autocomplete="off">
              <label class="btn btn-outline-success" for="mode_lunas">
                <i class="bi bi-check-circle me-1"></i>Bayar Lunas
              </label>

              <input type="radio" class="btn-check" name="mode_bayar" id="mode_cicil" value="cicil" autocomplete="off">
              <label class="btn btn-outline-primary" for="mode_cicil">
                <i class="bi bi-layers me-1"></i>Bayar Cicilan
              </label>
            </div>
          </div>

          <div class="card-body px-4 pb-4">

            <!-- Alert info -->
            <div id="info_lunas" class="alert alert-success border-0 py-2 small mb-3">
              <i class="bi bi-info-circle me-1"></i>
              Pembayaran admin langsung tercatat <strong>LUNAS</strong> tanpa verifikasi dan masuk ke kas yang dipilih.
              Jika ada kelebihan bayar, akan dicatat sebagai pemasukan tambahan ke kas yang dipilih.
            </div>
            <div id="info_cicil" class="alert alert-primary border-0 py-2 small mb-3" style="display:none">
              <i class="bi bi-info-circle me-1"></i>
              Mode cicilan: masukkan nominal yang dibayar sekarang. Sisa tagihan diperbarui otomatis.
            </div>

            <!-- ── NOMINAL LUNAS (auto-fill, bisa diubah untuk kelebihan) ── -->
            <div id="wrap_lunas_nominal" class="mb-3">
              <label class="form-label fw-semibold">
                Nominal Dibayar (Rp)
                <span class="text-danger">*</span>
                <span class="badge bg-success-subtle text-success border border-success-subtle ms-1" style="font-size:10px">
                  <i class="bi bi-magic me-1"></i>Otomatis sesuai tagihan
                </span>
              </label>
              <div class="input-group">
                <span class="input-group-text bg-light">Rp</span>
                <input type="number" name="nominal_lunas" id="nominal_lunas"
                       class="form-control form-control-lg fw-bold"
                       value="<?php echo $sisa; ?>"
                       min="<?php echo $sisa; ?>"
                       step="1000"
                       placeholder="<?php echo $sisa; ?>">
              </div>
              <div class="form-text">
                Tagihan: <strong class="text-success">Rp <?php echo number_format($sisa,0,',','.'); ?></strong>
                · Boleh diisi lebih jika ada kelebihan bayar
              </div>

              <!-- Preview kelebihan -->
              <div id="preview_lebih" class="mt-2 p-3 rounded border border-warning bg-warning bg-opacity-10" style="display:none">
                <div class="d-flex align-items-center gap-2 mb-2">
                  <i class="bi bi-exclamation-triangle-fill text-warning"></i>
                  <strong class="text-warning-emphasis small">Ada Kelebihan Bayar</strong>
                </div>
                <div class="d-flex justify-content-between small mb-1">
                  <span class="text-muted">Tagihan:</span>
                  <strong>Rp <?php echo number_format($sisa,0,',','.'); ?></strong>
                </div>
                <div class="d-flex justify-content-between small mb-1">
                  <span class="text-muted">Dibayar:</span>
                  <strong class="text-primary" id="preview_dibayar">-</strong>
                </div>
                <div class="d-flex justify-content-between small">
                  <span class="text-muted">Kelebihan:</span>
                  <strong class="text-warning" id="preview_kelebihan">-</strong>
                </div>
                <!-- Select kas kelebihan -->
                <div class="mt-2 pt-2 border-top border-warning">
                  <label class="form-label fw-semibold small mb-1">
                    Kelebihan masuk ke Kas: <span class="text-danger">*</span>
                  </label>
                  <select name="kas_kelebihan_id" id="kas_kelebihan_id" class="form-select form-select-sm">
                    <option value="">-- Pilih Kas --</option>
                    <?php foreach($kas_list as $k): ?>
                      <option value="<?php echo $k->id; ?>"><?php echo $k->nama; ?></option>
                    <?php endforeach; ?>
                  </select>
                  <div class="form-text text-warning-emphasis">
                    <i class="bi bi-info-circle me-1"></i>
                    Kelebihan akan dicatat sebagai <strong>tambahan <?php echo $iuran->nama_iuran; ?></strong>
                  </div>
                </div>
              </div>
            </div>

            <!-- Nominal Cicilan (muncul saat cicil) -->
            <div id="wrap_cicil" style="display:none" class="mb-3">
              <label class="form-label fw-semibold">Nominal Cicilan (Rp) <span class="text-danger">*</span></label>
              <input type="number" name="nominal_cicilan" id="nominal_cicilan"
                     class="form-control" min="1" max="<?php echo $sisa; ?>"
                     placeholder="Contoh: 10000">
              <div class="form-text">
                Sisa tagihan: <strong class="text-danger">Rp <?php echo number_format($sisa,0,',','.'); ?></strong>
              </div>
              <!-- Preview cicil -->
              <div id="preview_cicil" class="mt-2 p-2 rounded bg-light border" style="display:none;font-size:13px">
                <div class="d-flex justify-content-between">
                  <span class="text-muted">Dibayar sekarang:</span>
                  <strong class="text-success" id="preview_bayar">-</strong>
                </div>
                <div class="d-flex justify-content-between">
                  <span class="text-muted">Sisa setelah ini:</span>
                  <strong class="text-danger" id="preview_sisa">-</strong>
                </div>
              </div>
            </div>

            <!-- Tanggal + Metode + Kas -->
            <div class="row g-3 mb-3">
              <div class="col-md-4">
                <label class="form-label fw-semibold">Tanggal Bayar <span class="text-danger">*</span></label>
                <input type="date" name="tanggal_bayar" class="form-control"
                       value="<?php echo date('Y-m-d'); ?>" required>
              </div>
              <div class="col-md-4">
                <label class="form-label fw-semibold">Metode Pembayaran <span class="text-danger">*</span></label>
                <select name="metode_pembayaran" id="metode_pembayaran" class="form-select" required>
                  <option value="tunai">Tunai</option>
                  <option value="transfer">Transfer Bank</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label fw-semibold">Masuk ke Kas <span class="text-danger">*</span></label>
                <select name="master_kas_id" id="master_kas_id" class="form-select" required>
                  <option value="">-- Pilih Kas --</option>
                  <?php foreach($kas_list as $k): ?>
                    <option value="<?php echo $k->id; ?>"><?php echo $k->nama; ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>

            <!-- Bukti + Keterangan -->
            <div class="row g-3 mb-4">
              <div class="col-md-6">
                <label class="form-label fw-semibold">
                  Bukti Transfer <small class="text-muted fw-normal">(opsional)</small>
                </label>
                <input type="file" name="bukti_transfer" class="form-control" accept=".jpg,.jpeg,.png,.pdf">
                <div class="form-text"><i class="bi bi-paperclip"></i> JPG, PNG, PDF — maks. 2MB</div>
              </div>
              <div class="col-md-6">
                <label class="form-label fw-semibold">
                  Keterangan <small class="text-muted fw-normal">(opsional)</small>
                </label>
                <textarea name="keterangan" class="form-control" rows="3"
                          placeholder="Catatan tambahan..."></textarea>
              </div>
            </div>

            <!-- Tombol -->
            <div class="d-flex justify-content-between align-items-center">
              <a href="<?php echo base_url('iuran'); ?>" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left me-1"></i>Kembali
              </a>
              <button type="submit" class="btn btn-success px-4" id="btn_submit">
                <i class="bi bi-check-circle me-2"></i>
                <span id="btn_label">Simpan Pembayaran</span>
              </button>
            </div>

          </div>
        </div>
      </div>

    </div><!-- /row -->
  </form>
</div>

<script>
(function(){
  var sisa        = <?php echo (float)$sisa; ?>;
  var namaIuran   = <?php echo json_encode($iuran->nama_iuran); ?>;

  var elLunas         = document.getElementById('mode_lunas');
  var elCicil         = document.getElementById('mode_cicil');
  var wrapLunas       = document.getElementById('wrap_lunas_nominal');
  var wrapCicil       = document.getElementById('wrap_cicil');
  var inputLunas      = document.getElementById('nominal_lunas');
  var inputCicil      = document.getElementById('nominal_cicilan');
  var previewCicil    = document.getElementById('preview_cicil');
  var previewBayar    = document.getElementById('preview_bayar');
  var previewSisaEl   = document.getElementById('preview_sisa');
  var previewLebih    = document.getElementById('preview_lebih');
  var previewDibayar  = document.getElementById('preview_dibayar');
  var previewKelebihan= document.getElementById('preview_kelebihan');
  var kasKelebihanSel = document.getElementById('kas_kelebihan_id');
  var masterKasSel    = document.getElementById('master_kas_id');
  var infoLunas       = document.getElementById('info_lunas');
  var infoCicil       = document.getElementById('info_cicil');
  var btnLabel        = document.getElementById('btn_label');

  function rp(n) {
    return 'Rp ' + Math.max(0, Math.round(n)).toLocaleString('id-ID');
  }

  // Sync pilihan kas utama ke kas kelebihan (default sama)
  masterKasSel.addEventListener('change', function(){
    var val = this.value;
    // Set default kas kelebihan sama dengan kas utama jika belum dipilih
    if(kasKelebihanSel.value === '' || kasKelebihanSel.dataset.autoSet === '1') {
      kasKelebihanSel.value = val;
      kasKelebihanSel.dataset.autoSet = '1';
    }
  });
  kasKelebihanSel.addEventListener('change', function(){
    // User sudah pilih manual, jangan auto-override lagi
    this.dataset.autoSet = '0';
  });

  // Handler input nominal lunas
  inputLunas.addEventListener('input', function(){
    var val = parseFloat(this.value) || 0;
    if(val < sisa) val = sisa; // minimum = sisa tagihan

    var lebih = val - sisa;
    if(lebih > 0) {
      previewDibayar.textContent  = rp(val);
      previewKelebihan.textContent = rp(lebih);
      previewLebih.style.display  = 'block';
      // Auto-set kas kelebihan sesuai kas utama
      if(kasKelebihanSel.value === '' || kasKelebihanSel.dataset.autoSet !== '0') {
        kasKelebihanSel.value = masterKasSel.value;
        kasKelebihanSel.dataset.autoSet = '1';
      }
    } else {
      previewLebih.style.display = 'none';
    }
  });

  // Prevent nominal lunas < sisa
  inputLunas.addEventListener('blur', function(){
    var val = parseFloat(this.value) || 0;
    if(val < sisa) {
      this.value = sisa;
      previewLebih.style.display = 'none';
    }
  });

  // Handler input nominal cicilan
  inputCicil.addEventListener('input', function(){
    var val = parseFloat(this.value) || 0;
    if(val > sisa) { this.value = sisa; val = sisa; }
    if(val > 0) {
      previewBayar.textContent    = rp(val);
      previewSisaEl.textContent   = rp(sisa - val);
      previewCicil.style.display  = 'block';
    } else {
      previewCicil.style.display = 'none';
    }
  });

  function toggleMode() {
    var isCicil = elCicil.checked;
    wrapLunas.style.display   = isCicil ? 'none'  : 'block';
    wrapCicil.style.display   = isCicil ? 'block' : 'none';
    inputCicil.required       = isCicil;
    infoLunas.style.display   = isCicil ? 'none'  : 'block';
    infoCicil.style.display   = isCicil ? 'block' : 'none';
    btnLabel.textContent      = isCicil ? 'Simpan Cicilan' : 'Simpan Pembayaran';
    if(!isCicil) {
      // Reset nominal lunas ke sisa tagihan
      inputLunas.value = sisa;
      previewLebih.style.display = 'none';
    } else {
      previewCicil.style.display = 'none';
    }
  }

  elLunas.addEventListener('change', toggleMode);
  elCicil.addEventListener('change', toggleMode);
  toggleMode();
})();
</script>