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

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

<div class="row">
    <div class="col-md-4">
        <div class="card card-emerald card-outline shadow-sm">
            <div class="card-header bg-emerald text-white">
                <h3 class="card-title text-bold"><i class="fas fa-shopping-cart mr-2"></i> Form Penebusan</h3>
            </div>
            <form action="<?= base_url('transaksi/proses_penebusan') ?>" method="post" id="formPenebusan">
                <div class="card-body">
                    <div class="form-group">
                        <label>Petani (Penebus)</label>
                        <select name="id_petani" id="select_petani" class="form-control" required
                                oninvalid="this.setCustomValidity('Silakan pilih petani terlebih dahulu!')" 
                                oninput="this.setCustomValidity('')">
                            <option value="">-- Pilih Petani --</option>
                            <?php foreach ($petani as $p): ?>
                                <option value="<?= $p['id_petani'] ?>"><?= $p['nama_petani'] ?> (<?= $p['nik'] ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Pilih Pupuk</label>
                        <select name="id_pupuk" id="select_pupuk" class="form-control" required
                                oninvalid="this.setCustomValidity('Silakan pilih jenis pupuk terlebih dahulu!')" 
                                oninput="this.setCustomValidity('')">
                            <option value="" data-harga="0">-- Pilih Jenis Pupuk --</option>
                            <?php foreach ($pupuk as $pu): ?>
                                <option value="<?= $pu['id_pupuk'] ?>" data-harga="<?= $pu['harga_het'] ?>">
                                    <?= $pu['nama_pupuk'] ?> (Stok Gudang: <?= number_format($pu['stok_global'], 0, ',', '.') ?> Kg)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Sisa Kuota e-RDKK Petani (Kg)</label>
                        <input type="text" id="kuota_tampil" class="form-control text-bold bg-white" readonly value="Pilih petani dan pupuk dahulu..." style="color: #495057;">
                        <small class="text-danger d-none" id="warning_kuota">* Jumlah beli melebihi sisa kuota petani!</small>
                    </div>

                    <div class="form-group">
                        <label>Harga HET per Kg (Rp)</label>
                        <input type="text" id="harga_tampil" class="form-control" readonly value="Rp 0">
                    </div>

                    <div class="form-group">
                        <label>Jumlah Beli (Kg)</label>
                        <input type="number" name="jumlah_beli" id="input_jumlah" class="form-control" placeholder="Contoh: 50" required min="1"
                               oninvalid="this.setCustomValidity('Jumlah beli wajib diisi dengan angka bulat minimal 1 Kg!')" 
                               oninput="this.setCustomValidity('')">
                    </div>

                    <div class="form-group bg-light p-3 border rounded border-emerald">
                        <label class="text-emerald">Total Pembayaran (Rp)</label>
                        <h3 class="mb-0 font-weight-bold" id="total_bayar_tampil">Rp 0</h3>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-emerald btn-block btn-lg font-weight-bold" id="btn_submit_transaksi">
                        <i class="fas fa-check-circle mr-1"></i> Proses Transaksi
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card card-emerald card-outline shadow-sm">
            <div class="card-header d-flex justify-content-between align-items-center row">
                <div class="col-sm-6">
                    <h3 class="card-title text-bold py-1">Riwayat Penebusan Terbaru</h3>
                </div>
                <div class="col-sm-6">
                    <div class="input-group input-group-sm">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-white border-right-0"><i class="fas fa-search text-muted"></i></span>
                        </div>
                        <input type="text" id="search_transaksi" class="form-control border-left-0" placeholder="Ketik No. Invoice / Nama Petani / Pupuk...">
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <table class="table table-hover table-striped mb-0" id="table_riwayat">
                    <thead class="bg-light">
                        <tr>
                            <th>Detail Transaksi</th>
                            <th>Tanggal</th>
                            <th>Jumlah (Kg)</th>
                            <th>Total Bayar</th>
                            <th class="text-center" width="15%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($transaksi)): ?>
                            <tr id="row_kosong">
                                <td colspan="5" class="text-center text-muted py-4">Belum ada transaksi penebusan.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($transaksi as $t): ?>
                                <tr>
                                    <td>
                                        <span class="badge badge-info mb-1"><?= $t['no_invoice'] ?></span><br>
                                        <span class="text-sm font-weight-bold text-dark"><?= $t['nama_petani'] ?></span><br>
                                        <small class="text-muted"><i class="fas fa-leaf text-xs mr-1"></i> <?= $t['nama_pupuk'] ?></small>
                                    </td>
                                    <td><span class="text-sm"><?= date('d/m/Y H:i', strtotime($t['tanggal_transaksi'])) ?></span></td>
                                    <td><b><?= number_format($t['jumlah_beli'], 0, ',', '.') ?> Kg</b></td>
                                    <td class="text-success text-bold">Rp <?= number_format($t['total_bayar'], 0, ',', '.') ?></td>
                                    <td class="text-center" style="vertical-align: middle;">
                                        <a href="<?= base_url('transaksi/cetak_nota/' . $t['id_transaksi']) ?>" target="_blank" class="btn btn-xs btn-emerald shadow-sm">
                                            <i class="fas fa-print mr-1"></i> Cetak Nota
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        <tr id="pencarian_kosong" class="d-none">
                            <td colspan="5" class="text-center text-muted py-4"><i class="fas fa-search-minus mr-1"></i> Data transaksi tidak ditemukan.</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // 1. DATA ALOKASI KUOTA DARI CONTROLLER
        const arrayKuota = <?= json_encode($kuota_all ?? []) ?>;

        const selectPetani = document.getElementById('select_petani');
        const selectPupuk = document.getElementById('select_pupuk');
        const inputJumlah = document.getElementById('input_jumlah');
        const hargaTampil = document.getElementById('harga_tampil');
        const kuotaTampil = document.getElementById('kuota_tampil');
        const totalBayarTampil = document.getElementById('total_bayar_tampil');
        const warningKuota = document.getElementById('warning_kuota');
        const btnSubmit = document.getElementById('btn_submit_transaksi');

        let sisaKuotaAktif = 0;

        function formatRupiah(angka) {
            return new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR',
                minimumFractionDigits: 0
            }).format(angka);
        }

        function cekKuotaDanHitung() {
            const idPetani = selectPetani.value;
            const idPupuk = selectPupuk.value;
            
            const selectedOption = selectPupuk.options[selectPupuk.selectedIndex];
            let harga = selectedOption ? (selectedOption.getAttribute('data-harga') || 0) : 0;
            let jumlah = parseInt(inputJumlah.value) || 0;

            hargaTampil.value = formatRupiah(harga);

            if (idPetani && idPupuk) {
                const cocok = arrayKuota.find(k => k.id_petani == idPetani && k.id_pupuk == idPupuk);

                if (cocok) {
                    let jatah = parseInt(cocok.jatah_kg) || 0;
                    let terpakai = parseInt(cocok.terpakai_kg) || 0;
                    sisaKuotaAktif = jatah - terpakai;
                    kuotaTampil.value = sisaKuotaAktif + " Kg";
                } else {
                    sisaKuotaAktif = 0;
                    kuotaTampil.value = "0 Kg (Kuota Belum Diatur)";
                }
            } else {
                sisaKuotaAktif = 0;
                kuotaTampil.value = "Pilih petani dan pupuk dahulu...";
            }

            if (harga > 0 && jumlah > 0) {
                let total = harga * jumlah;
                totalBayarTampil.innerText = formatRupiah(total);
            } else {
                totalBayarTampil.innerText = "Rp 0";
            }

            if (jumlah > sisaKuotaAktif && idPetani && idPupuk) {
                warningKuota.classList.remove('d-none');
                kuotaTampil.style.borderColor = '#dc3545';
                kuotaTampil.style.backgroundColor = '#f8d7da';
                btnSubmit.disabled = true;
            } else {
                warningKuota.classList.add('d-none');
                kuotaTampil.style.borderColor = '#ced4da';
                kuotaTampil.style.backgroundColor = '#ffffff';
                btnSubmit.disabled = false;
            }
        }

        selectPetani.addEventListener('change', cekKuotaDanHitung);
        selectPupuk.addEventListener('change', cekKuotaDanHitung);
        inputJumlah.addEventListener('input', cekKuotaDanHitung);

        document.getElementById('formPenebusan').addEventListener('submit', function(e) {
            let jumlah = parseInt(inputJumlah.value) || 0;
            if (jumlah > sisaKuotaAktif) {
                e.preventDefault();
                alert('⚠️ Transaksi Ditolak! Jumlah pembelian melebihi sisa alokasi kuota petani.');
            }
        });

        // ===================================================================
        // 2. LOGIKA FITUR SEARCH ENGINE INSTAN (REAL-TIME FILTERING)
        // ===================================================================
        const searchInput = document.getElementById('search_transaksi');
        const tableRows = document.querySelectorAll('#table_riwayat tbody tr:not(#pencarian_kosong):not(#row_kosong)');
        const pencarianKosongRow = document.getElementById('pencarian_kosong');

        searchInput.addEventListener('input', function() {
            const keyword = searchInput.value.toLowerCase().trim();
            let adaDataCocok = false;

            tableRows.forEach(row => {
                // Mengambil seluruh teks di dalam baris (Invoice, Nama, Jenis Pupuk)
                const textBaris = row.textContent.toLowerCase();

                if (textBaris.includes(keyword)) {
                    row.classList.remove('d-none'); // Tampilkan baris jika cocok
                    adaDataCocok = true;
                } else {
                    row.classList.add('d-none'); // Sembunyikan baris jika tidak cocok
                }
            });

            // Tampilkan baris penanda khusus "Data tidak ditemukan" jika semua baris tersembunyi
            if (!adaDataCocok && keyword !== "") {
                pencarianKosongRow.classList.remove('d-none');
            } else {
                pencarianKosongRow.classList.add('d-none');
            }
        });
    });
</script>

<?= $this->endSection() ?>