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

<?= $this->section('content') ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<ul class="nav nav-pills mb-3">
    <li class="nav-item">
        <a class="nav-link active rounded-pill small fw-bold" href="<?= base_url('approval') ?>">Antrean Pengajuan</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-muted rounded-pill small fw-bold" href="<?= base_url('approval/riwayat') ?>">Riwayat Selesai</a>
    </li>
</ul>

<div class="mb-4 d-flex justify-content-between align-items-end">
    <div>
        <h5 class="fw-bold text-dark">Antrean Approval Izin / Sakit / DL</h5>
        <p class="text-muted small mb-0">Daftar pengajuan baru (Status: Pending).</p>
    </div>
    <div id="bulkActionArea" style="display: none;">
        <button type="button" class="btn btn-success btn-sm rounded-pill px-3 fw-bold shadow-sm" onclick="bulkApprove('setuju')">
            <i class="fas fa-check-double me-1"></i> Setujui Terpilih (<span id="countSelected">0</span>)
        </button>
        <button type="button" class="btn btn-danger btn-sm rounded-pill px-3 fw-bold shadow-sm" onclick="bulkApprove('tolak')">
            <i class="fas fa-times-circle me-1"></i> Tolak Terpilih
        </button>
    </div>
</div>

<div class="card border-0 shadow-sm mb-3" style="border-radius: 15px;">
    <div class="card-body py-3">
        <form action="<?= base_url('approval') ?>" method="GET" class="row g-2">
            <?php if (in_array(session()->get('level'), ['Superadmin', 'kabupaten'])): ?>
            <div class="col-md-5">
                <select name="id_opd" class="form-select form-select-sm border-light bg-light">
                    <option value="">-- Semua OPD --</option>
                    <?php foreach($list_opd as $o): ?>
                        <option value="<?= $o['id_opd'] ?>" <?= ($selected_opd == $o['id_opd']) ? 'selected' : '' ?>><?= $o['nama_opd'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            
            <div class="<?= in_array(session()->get('level'), ['Superadmin', 'kabupaten']) ? 'col-md-5' : 'col-md-10' ?>">
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-light border-light"><i class="fas fa-search text-muted"></i></span>
                    <input type="text" name="keyword" class="form-control border-light bg-light" placeholder="Cari Nama Pegawai atau NIP..." value="<?= $keyword ?? '' ?>">
                </div>
            </div>
            
            <div class="col-md-2 d-grid">
                <button type="submit" class="btn btn-sm btn-primary rounded-pill fw-bold">Cari Data</button>
            </div>
        </form>
    </div>
</div>

<div class="card border-0 shadow-sm" style="border-radius: 15px; overflow: hidden;">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0 text-center">
                <thead class="bg-light">
                    <tr class="text-muted small uppercase">
                        <th class="ps-4 py-3 text-start">
                            <input type="checkbox" class="form-check-input" id="checkAll">
                        </th>
                        <th class="text-start">TANGGAL PENGAJUAN</th>
                        <th class="text-start">PEGAWAI</th>
                        <th>KATEGORI & SLOT</th>
                        <th>FILE BUKTI</th>
                        <th>STATUS</th>
                        <th>AKSI</th>
                    </tr>
                </thead>
                <tbody class="small text-dark">
                    <?php if (empty($pengajuan)): ?>
                        <tr><td colspan="7" class="py-5 text-muted">Tidak ada antrean pengajuan baru.</td></tr>
                    <?php endif; ?>

                    <?php foreach ($pengajuan as $p): ?>
                        <tr>
                            <td class="ps-4 text-start">
                                <input type="checkbox" class="form-check-input rowCheck" value="<?= $p['id_pengajuan'] ?>">
                            </td>
                            <td class="text-start">
                                <div class="fw-bold text-primary">
                                    <?= date('d/m/Y', strtotime($p['tanggal_mulai'])) ?> 
                                    <?= ($p['tanggal_mulai'] != $p['tanggal_selesai']) ? 's/d ' . date('d/m/Y', strtotime($p['tanggal_selesai'])) : '' ?>
                                </div>
                                <span class="text-muted" style="font-size: 0.65rem;">Ket: <?= substr($p['keterangan'], 0, 30) ?>...</span>
                            </td>
                            <td class="text-start">
                                <div class="fw-bold"><?= $p['nama_lengkap'] ?></div>
                                <div class="text-muted" style="font-size: 0.7rem;">NIP. <?= $p['nip'] ?></div>
                            </td>
                            <td>
                                <span class="badge bg-info bg-opacity-10 text-info border border-info border-opacity-25 px-2 mb-1">
                                    <?= $p['kategori'] ?>
                                </span>
                                <div class="text-muted" style="font-size: 0.7rem;">
                                    <i class="far fa-clock"></i> Sesi: <?= $p['slot_waktu'] ?? 'Penuh' ?>
                                </div>
                            </td>
                            <td>
                                <?php if($p['file_bukti']): ?>
                                    <a href="<?= base_url('uploads/bukti_absen/' . $p['file_bukti']) ?>" target="_blank" class="btn btn-sm btn-light border rounded-pill px-3 text-primary shadow-sm" style="font-size: 0.75rem; font-weight: 600;">
                                        <i class="fas fa-file-image me-1"></i> Bukti
                                    </a>
                                <?php else: ?>
                                    <span class="text-muted fst-italic">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25 px-2">Pending</span>
                            </td>
                            <td class="pe-4">
                                <div class="d-flex justify-content-center gap-1">
                                    <button type="button" class="btn btn-sm btn-outline-success rounded-circle" title="Setujui Pengajuan" onclick="modalApproval('<?= $p['id_pengajuan'] ?>', '<?= addslashes($p['nama_lengkap']) ?>', '<?= $p['kategori'] ?>', 'setuju')">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-danger rounded-circle" title="Tolak Pengajuan" onclick="modalApproval('<?= $p['id_pengajuan'] ?>', '<?= addslashes($p['nama_lengkap']) ?>', '<?= $p['kategori'] ?>', 'tolak')">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <?php if ($pager): ?>
        <div class="card-footer bg-white border-0 py-3 text-center"><?= $pager ?></div>
    <?php endif; ?>
</div>

<div class="modal fade" id="modalApproval" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px;">
            <div class="modal-header border-0 p-4 pb-2">
                <h6 class="fw-bold mb-0" id="modalTitle">Proses Pengajuan</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="<?= base_url('approval/proses') ?>" method="POST">
                <?= csrf_field() ?>
                <div class="modal-body p-4 pt-2">
                    <input type="hidden" name="id_pengajuan" id="m_id_pengajuan">
                    <input type="hidden" name="aksi" id="m_aksi">

                    <p class="small text-muted mb-3">Tindakan untuk pengajuan <strong id="m_nama_pegawai" class="text-dark fs-6"></strong></p>

                    <div class="mb-4">
                        <label class="small fw-bold text-dark mb-2">Catatan Admin (Wajib diisi jika ditolak)</label>
                        <textarea name="catatan" id="m_catatan" class="form-control bg-light border-0 rounded-3" rows="3" placeholder="Tulis alasan atau catatan..."></textarea>
                    </div>

                    <button type="submit" id="btnSubmitModal" class="btn w-100 rounded-pill fw-bold shadow-sm">Simpan Keputusan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    const checkAll = document.getElementById('checkAll');
    const rowChecks = document.querySelectorAll('.rowCheck');
    const bulkActionArea = document.getElementById('bulkActionArea');
    const countSelected = document.getElementById('countSelected');

    function updateBulkArea() {
        const checkedCount = document.querySelectorAll('.rowCheck:checked').length;
        bulkActionArea.style.display = checkedCount > 0 ? 'block' : 'none';
        countSelected.innerText = checkedCount;
    }

    checkAll.addEventListener('change', function() {
        rowChecks.forEach(cb => cb.checked = this.checked);
        updateBulkArea();
    });

    rowChecks.forEach(cb => {
        cb.addEventListener('change', updateBulkArea);
    });

    // FUNGSI MODAL DINAMIS
    function modalApproval(id, nama, kategori, aksi) {
        document.getElementById('m_id_pengajuan').value = id;
        document.getElementById('m_aksi').value = aksi;
        document.getElementById('m_nama_pegawai').innerText = nama + " (" + kategori + ")";
        
        const btnSubmit = document.getElementById('btnSubmitModal');
        const modalTitle = document.getElementById('modalTitle');
        const catatanInput = document.getElementById('m_catatan');

        if(aksi === 'setuju') {
            modalTitle.innerText = "Setujui Pengajuan";
            btnSubmit.className = "btn btn-success w-100 rounded-pill fw-bold shadow-sm";
            btnSubmit.innerText = "Setujui & Masukkan ke Presensi";
            catatanInput.required = false;
        } else {
            modalTitle.innerText = "Tolak Pengajuan";
            btnSubmit.className = "btn btn-danger w-100 rounded-pill fw-bold shadow-sm";
            btnSubmit.innerText = "Tolak Pengajuan";
            catatanInput.required = true; // Wajib isi alasan jika ditolak
        }

        new bootstrap.Modal(document.getElementById('modalApproval')).show();
    }

    function bulkApprove(aksi) {
        const selectedIds = Array.from(document.querySelectorAll('.rowCheck:checked')).map(cb => cb.value);
        
        Swal.fire({
            title: `Konfirmasi ${aksi == 'setuju' ? 'Persetujuan' : 'Penolakan'} Massal`,
            text: `Anda akan memproses ${selectedIds.length} pengajuan sekaligus. ${aksi == 'tolak' ? 'Pengajuan ini tidak akan masuk ke tabel presensi.' : ''} Lanjutkan?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Ya, Proses Semua',
            confirmButtonColor: aksi == 'setuju' ? '#10b981' : '#ef4444'
        }).then((result) => {
            if (result.isConfirmed) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = "<?= base_url('approval/proses_massal') ?>"; 
                
                const addField = (name, value) => {
                    const field = document.createElement('input');
                    field.type = 'hidden';
                    field.name = name;
                    field.value = value;
                    form.appendChild(field);
                };

                addField('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
                addField('ids', JSON.stringify(selectedIds));
                addField('aksi', aksi);
                
                document.body.appendChild(form);
                form.submit();
            }
        });
    }
</script>
<?= $this->endSection() ?>