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

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

<?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success alert-dismissible fade show mb-3" role="alert">
        <i class="fas fa-check-circle mr-2"></i> <?= session()->getFlashdata('success') ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
<?php endif; ?>

<div class="card card-emerald card-outline shadow">
    <div class="card-header">
        <h3 class="card-title">Daftar Anggota Kelompok Tani</h3>
        <div class="card-tools">
            <button class="btn btn-emerald btn-sm" data-toggle="modal" data-target="#modalTambah">
                <i class="fas fa-plus"></i> Tambah Baru
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        <table class="table table-hover table-striped mb-0">
    <thead class="bg-light">
        <tr>
            <th width="5%" class="text-center">No</th>
            <th>NIK</th>
            <th>Nama Petani</th>
            <th>Alamat</th> <!-- TAMBAHAN HEADER ALAMAT -->
            <th>Blok Lahan</th>
            <th>Luas (Ha)</th>
            <th class="text-center" width="15%">Aksi</th>
        </tr>
    </thead>
    <tbody>
        <?php $no = 1; foreach ($petani as $p) : ?>
            <tr>
                <td class="text-center"><?= $no++ ?></td>
                <td><span class="badge badge-light border border-secondary"><?= $p['nik'] ?></span></td>
                <td><b><?= $p['nama_petani'] ?></b></td>
                <td><?= $p['alamat'] ?></td> <!-- TAMBAHAN ISI DATA ALAMAT -->
                <td><?= $p['kelompok_blok'] ?></td>
                <td><span class="badge badge-success bg-emerald"><?= number_format($p['luas_lahan'], 2) ?> Ha</span></td>
                <td class="text-center">
                    <button class="btn btn-xs btn-info btn-edit"
                        data-id="<?= $p['id_petani'] ?>"
                        data-nik="<?= $p['nik'] ?>"
                        data-nama="<?= $p['nama_petani'] ?>"
                        data-alamat="<?= $p['alamat'] ?>"
                        data-luas="<?= $p['luas_lahan'] ?>"
                        data-blok="<?= $p['kelompok_blok'] ?>"
                        data-toggle="modal" data-target="#modalEdit" title="Edit Data">
                        <i class="fas fa-edit"></i>
                    </button>
                    <a href="<?= base_url('petani/hapus/' . $p['id_petani']) ?>" class="btn btn-xs btn-danger" onclick="return confirm('Apakah Anda yakin ingin menghapus data petani ini?')" title="Hapus Data">
                        <i class="fas fa-trash"></i>
                    </a>
                </td>
            </tr>
        <?php endforeach; ?>
        <?php if (empty($petani)): ?>
            <tr>
                <!-- PERBAIKAN: colspan diubah dari 6 menjadi 7 karena jumlah kolom bertambah -->
                <td colspan="7" class="text-center text-muted py-4">Belum ada data petani yang terdaftar dalam sistem.</td>
            </tr>
        <?php endif; ?>
    </tbody>
</table>
    </div>
</div>

<div class="modal fade" id="modalTambah" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-emerald text-white">
                <h5 class="modal-title"><i class="fas fa-user-plus mr-2"></i> Tambah Data Petani</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <form id="formTambahPetani" action="<?= base_url('petani/simpan') ?>" method="post">
                <div class="modal-body">
                   <div class="form-group">
                        <label>NIK (Nomor Induk Kependudukan) <span class="text-danger">*</span></label>
                        <input type="text" name="nik" inputmode="numeric" class="form-control" placeholder="Masukkan 16 digit NIK angka" 
                               required minlength="16" maxlength="16" pattern="\d{16}"
                               oninvalid="this.setCustomValidity('NIK wajib diisi tepat 16 digit angka murni!')" 
                               oninput="this.setCustomValidity('')">
                    </div>
                    <div class="form-group">
                        <label>Nama Petani <span class="text-danger">*</span></label>
                        <input type="text" name="nama_petani" class="form-control" placeholder="Nama lengkap sesuai KTP" 
                               required
                               oninvalid="this.setCustomValidity('Nama petani wajib diisi!')" 
                               oninput="this.setCustomValidity('')">
                    </div>
                    <div class="form-group">
                        <label>Alamat Lengkap <span class="text-danger">*</span></label>
                        <textarea name="alamat" class="form-control" rows="2" placeholder="Alamat domisili tempat tinggal" 
                                  required
                                  oninvalid="this.setCustomValidity('Alamat lengkap wajib diisi!')" 
                                  oninput="this.setCustomValidity('')"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Kelompok Blok Lahan <span class="text-danger">*</span></label>
                                <input type="text" name="kelompok_blok" class="form-control" placeholder="Contoh: Blok A" 
                                       required
                                       oninvalid="this.setCustomValidity('Kelompok blok lahan wajib diisi!')" 
                                       oninput="this.setCustomValidity('')">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Luas Lahan (Ha) <span class="text-danger">*</span></label>
                                <input type="number" step="0.01" name="luas_lahan" class="form-control" placeholder="Contoh: 0.5" 
                                       required min="0.01"
                                       oninvalid="this.setCustomValidity('Luas lahan wajib diisi dengan angka valid (Minimal 0.01)!')" 
                                       oninput="this.setCustomValidity('')">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-emerald">Simpan Data</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEdit" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><i class="fas fa-user-edit mr-2"></i> Edit Data Petani</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <form id="formEditPetani" method="post">
                <div class="modal-body">
                    <div class="form-group">
                        <label>NIK <span class="text-danger">*</span></label>
                        <input type="text" name="nik" inputmode="numeric" class="form-control" required minlength="16" maxlength="16" pattern="\d{16}"
                               oninvalid="this.setCustomValidity('NIK hasil perubahan wajib berisi tepat 16 digit angka murni!')" 
                               oninput="this.setCustomValidity('')">
                    </div>
                    <div class="form-group">
                        <label>Nama Petani <span class="text-danger">*</span></label>
                        <input type="text" name="nama_petani" class="form-control" required
                               oninvalid="this.setCustomValidity('Nama petani tidak boleh dikosongkan!')" 
                               oninput="this.setCustomValidity('')">
                    </div>
                    <div class="form-group">
                        <label>Alamat <span class="text-danger">*</span></label>
                        <textarea name="alamat" class="form-control" rows="2" required
                                  oninvalid="this.setCustomValidity('Alamat tidak boleh dikosongkan!')" 
                                  oninput="this.setCustomValidity('')"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Kelompok Blok <span class="text-danger">*</span></label>
                                <input type="text" name="kelompok_blok" class="form-control" required
                                       oninvalid="this.setCustomValidity('Kelompok blok tidak boleh dikosongkan!')" 
                                       oninput="this.setCustomValidity('')">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Luas Lahan (Ha) <span class="text-danger">*</span></label>
                                <input type="number" step="0.01" name="luas_lahan" class="form-control" required min="0.01"
                                       oninvalid="this.setCustomValidity('Luas lahan hasil perubahan wajib diisi angka valid (Minimal 0.01)!')" 
                                       oninput="this.setCustomValidity('')">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-info">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // 1. LOGIKA UTAMA: MIGRASI DATA KE MODAL EDIT
        const tombolEdit = document.querySelectorAll('.btn-edit');
        const formEdit = document.getElementById('formEditPetani');
        
        tombolEdit.forEach(button => {
            button.addEventListener('click', function() {
                const id = button.getAttribute('data-id');
                formEdit.setAttribute('action', '<?= base_url('petani/update') ?>/' + id);

                // Mengisi input modal edit berdasarkan selector tag name yang spesifik
                formEdit.querySelector('input[name="nik"]').value = button.getAttribute('data-nik');
                formEdit.querySelector('input[name="nama_petani"]').value = button.getAttribute('data-nama');
                formEdit.querySelector('textarea[name="alamat"]').value = button.getAttribute('data-alamat');
                formEdit.querySelector('input[name="luas_lahan"]').value = button.getAttribute('data-luas');
                formEdit.querySelector('input[name="kelompok_blok"]').value = button.getAttribute('data-blok');
            });
        });

        // ===================================================================
        // 2. SISTEM PENGUNCI KARAKTER FIELD BERTENAGA ATRIBUT NAME (ANTI ACCIDENT)
        // ===================================================================
        
        // Sasar semua input yang memiliki name="nik" (Baik di Modal Tambah maupun Edit)
        document.querySelectorAll('input[name="nik"]').forEach(input => {
            // Blokir keyboard fisik sebelum karakter dicetak ke layar
            input.addEventListener('keypress', function(e) {
                if (!/[0-9]/.test(e.key)) {
                    e.preventDefault();
                }
            });

            // Pembersihan instan jika menggunakan keyboard virtual HP/Televisi/Autofill
            input.addEventListener('input', function() {
                this.value = this.value.replace(/[^0-9]/g, '');
            });

            // Blokir jika ada teks campuran huruf yang di-copy paste masuk
            input.addEventListener('paste', function(e) {
                e.preventDefault();
                const text = (e.clipboardData || window.clipboardData).getData('text');
                this.value = text.replace(/[^0-9]/g, '').substring(0, 16);
            });
        });

        // Sasar semua input yang memiliki name="nama_petani" (Hanya Huruf & Spasi)
        document.querySelectorAll('input[name="nama_petani"]').forEach(input => {
            input.addEventListener('keypress', function(e) {
                if (!/[a-zA-Z\s]/.test(e.key)) {
                    e.preventDefault();
                }
            });

            input.addEventListener('input', function() {
                this.value = this.value.replace(/[^a-zA-Z\s]/g, '');
            });

            input.addEventListener('paste', function(e) {
                e.preventDefault();
                const text = (e.clipboardData || window.clipboardData).getData('text');
                this.value = text.replace(/[^a-zA-Z\s]/g, '');
            });
        });

        // Sasar semua input yang memiliki name="luas_lahan" (Blokir tombol eksponensial e/E/+/-)
        document.querySelectorAll('input[name="luas_lahan"]').forEach(input => {
            input.addEventListener('keydown', function(e) {
                if (['e', 'E', '+', '-'].includes(e.key)) {
                    e.preventDefault();
                }
            });
        });

        // 3. BARISAN VALIDASI AKHIR SAAT TOMBOL SIMPAN DIKLIK
        document.getElementById('formTambahPetani').addEventListener('submit', function(e) {
            const nikValue = this.querySelector('input[name="nik"]').value;
            if (nikValue.length !== 16) {
                e.preventDefault(); 
                alert('⚠️ Validasi Gagal! Nomor NIK harus berjumlah tepat 16 digit angka.');
                this.querySelector('input[name="nik"]').focus();
            }
        });

        formEdit.addEventListener('submit', function(e) {
            const nikEditValue = this.querySelector('input[name="nik"]').value;
            if (nikEditValue.length !== 16) {
                e.preventDefault(); 
                alert('⚠️ Validasi Gagal! Nomor NIK perubahan harus berjumlah tepat 16 digit angka.');
                this.querySelector('input[name="nik"]').focus();
            }
        });
    });
</script>

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