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

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

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

<style>
    /* Custom Styling untuk Loading DataTables */
    div.dataTables_processing {
        background-color: rgba(255, 255, 255, 0.9) !important;
        border: none !important;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        border-radius: 10px;
        padding: 15px !important;
        font-weight: bold;
        color: #0d6efd !important;
        z-index: 1055 !important;
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h5 class="fw-bold mb-0">Plotting Shift Pegawai</h5>
    <div>
        <button class="btn btn-danger btn-sm rounded-pill px-3 shadow-sm me-2" data-bs-toggle="modal" data-bs-target="#modalHapusMassal">
            <i class="fas fa-trash-alt me-1"></i> Hapus Massal
        </button>
        <button class="btn btn-primary btn-sm rounded-pill px-3 shadow-sm me-2" data-bs-toggle="modal" data-bs-target="#modalPlot">
            <i class="fas fa-plus me-1"></i> Manual
        </button>
        <button class="btn btn-success btn-sm rounded-pill px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#modalPlotMassal">
            <i class="fas fa-layer-group me-1"></i> Plot Massal
        </button>
    </div>
</div>

<?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i><?= session()->getFlashdata('success') ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if (session()->getFlashdata('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i><?= session()->getFlashdata('error') ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <div class="table-responsive">
            <table id="tablePlotting" class="table table-hover align-middle mb-0 w-100">
                <thead class="bg-light text-muted small">
                    <tr>
                        <th class="ps-4">TANGGAL</th>
                        <th>NAMA PEGAWAI</th>
                        <th>NAMA SHIFT</th>
                        <th class="text-center" width="10%">AKSI</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalPlot" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light border-0">
                <h6 class="modal-title fw-bold">Plotting Harian</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="formSimpanManual" action="<?= base_url('plotting/simpan') ?>" method="POST">
                <?= csrf_field() ?>
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="small fw-bold">Pegawai</label>
                        <select name="id_pegawai" class="form-select bg-light border-light select2-manual" required>
                            <option value="">-- Cari Nama Pegawai --</option>
                            <?php foreach ($pegawai as $pg): ?>
                                <option value="<?= $pg['id_pegawai'] ?>"><?= $pg['nama_lengkap'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">Pilih Shift</label>
                        <select name="id_jam_kerja" class="form-select bg-light border-light" required>
                            <?php foreach ($jam_kerja as $jk): ?>
                                <option value="<?= $jk['id_jam_kerja'] ?>"><?= $jk['nama_jadwal'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">Tanggal Dinas</label>
                        <input type="date" name="tanggal" class="form-control bg-light border-light" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100 rounded-pill">Simpan Jadwal</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalPlotMassal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-success text-white border-0">
                <h6 class="modal-title fw-bold"><i class="fas fa-layer-group me-2"></i>Plotting Massal</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="formSimpanMassal" action="<?= base_url('plotting/simpan_massal') ?>" method="POST">
                <?= csrf_field() ?>
                <div class="modal-body p-4">

                    <label class="small fw-bold mb-2">Target Jadwal</label>
                    <div class="d-flex gap-3 mb-3">
                        <?php if (in_array(session()->get('level'), ['Superadmin', 'kabupaten'])): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="scope" id="scopeGlobal" value="global" onclick="toggleScope()" checked>
                                <label class="form-check-label small" for="scopeGlobal">Semua ASN (Global)</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="scope" id="scopeOPD" value="opd" onclick="toggleScope()">
                                <label class="form-check-label small" for="scopeOPD">Per OPD</label>
                            </div>
                        <?php else: ?>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="scope" id="scopeGlobal" value="global" onclick="toggleScope()" checked>
                                <label class="form-check-label small" for="scopeGlobal">Seluruh Pegawai (OPD Anda)</label>
                            </div>
                        <?php endif; ?>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="scope" id="scopePegawai" value="pegawai" onclick="toggleScope()">
                            <label class="form-check-label small" for="scopePegawai">Pilih Pegawai</label>
                        </div>
                    </div>

                    <div class="p-3 bg-light rounded border mb-3">
                        <div id="boxGlobal" class="text-muted small">
                            <i class="fas fa-info-circle me-1"></i> Jadwal akan diterapkan ke <b>seluruh pegawai</b> sesuai filter di atas.
                        </div>

                        <?php if (in_array(session()->get('level'), ['Superadmin', 'kabupaten'])): ?>
                            <div id="boxOPD" class="d-none">
                                <label class="small fw-bold">Pilih OPD</label>
                                <select name="id_opd" class="form-select border-success select2-massal">
                                    <option value="">-- Pilih Dinas/Badan --</option>
                                    <?php foreach ($opd as $o): ?>
                                        <option value="<?= $o['id_opd'] ?>"><?= $o['nama_opd'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        <?php endif; ?>

                        <div id="boxPegawai" class="d-none">
                            <label class="small fw-bold">Pilih Pegawai (Bisa Lebih Dari 1)</label>
                            <select name="target_pegawai[]" class="form-select border-success select2-massal-multiple" multiple="multiple">
                                <?php foreach ($pegawai as $pg): ?>
                                    <option value="<?= $pg['id_pegawai'] ?>"><?= $pg['nama_lengkap'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="small fw-bold">Pilih Shift / Jam Kerja</label>
                        <select name="id_jam_kerja" class="form-select bg-light border-light" required>
                            <?php foreach ($jam_kerja as $jk): ?>
                                <option value="<?= $jk['id_jam_kerja'] ?>"><?= $jk['nama_jadwal'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <hr class="text-muted">

                    <div class="mb-3">
                        <label class="small fw-bold mb-2">Metode Pilih Tanggal</label>
                        <div class="d-flex gap-3">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="tipe_tanggal" id="tipeRange" value="range" onclick="toggleTipeTanggal()" checked>
                                <label class="form-check-label small" for="tipeRange">Rentang Tanggal (Awal-Akhir)</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="tipe_tanggal" id="tipeMulti" value="multiple" onclick="toggleTipeTanggal()">
                                <label class="form-check-label small" for="tipeMulti">Pilih Beberapa Tanggal</label>
                            </div>
                        </div>
                    </div>

                    <div class="row" id="boxRangeTanggal">
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">Dari Tanggal</label>
                            <input type="date" name="tgl_mulai" class="form-control bg-light border-light">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">Sampai Tanggal</label>
                            <input type="date" name="tgl_selesai" class="form-control bg-light border-light">
                        </div>
                    </div>

                    <div class="mb-3 d-none" id="boxMultiTanggal">
                        <label class="small fw-bold">Pilih Tanggal Acak (Bisa Lebih Dari 1)</label>
                        <input type="text" name="tanggal_multiple" id="flatpickr-multi" class="form-control border-success bg-white" placeholder="Klik untuk memilih tanggal...">
                    </div>

                    <div class="alert alert-warning small py-2 mb-0">
                        <i class="fas fa-exclamation-triangle me-1"></i> Data jadwal lama di tanggal tersebut akan <b>ditimpa</b>.
                    </div>

                    <br>
                    <button type="submit" class="btn btn-success w-100 rounded-pill fw-bold">Terapkan Jadwal Massal</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalHapusMassal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-danger text-white border-0">
                <h6 class="modal-title fw-bold"><i class="fas fa-exclamation-triangle me-2"></i>Hapus Jadwal Massal</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="formHapusMassal" action="<?= base_url('plotting/hapus_massal') ?>" method="POST">
                <?= csrf_field() ?>
                <div class="modal-body p-4">
                    <div class="alert alert-warning small border-0">
                        <i class="fas fa-info-circle me-1"></i> Pilih kriteria data yang ingin dihapus secara permanen.
                    </div>
                    
                    <div class="mb-3">
                        <label class="small fw-bold">Scope Penghapusan</label>
                        <select name="scope_hapus" class="form-select form-select-sm" id="scopeHapus" onchange="toggleScopeHapus()">
                            <?php if (in_array(session()->get('level'), ['Superadmin', 'kabupaten'])): ?>
                                <option value="global">Semua ASN (Global)</option>
                                <option value="opd">Per OPD / Instansi</option>
                            <?php else: ?>
                                <option value="global">Seluruh Pegawai (OPD Anda)</option>
                            <?php endif; ?>
                            <option value="pegawai">Pilih Beberapa Pegawai</option>
                        </select>
                    </div>

                    <?php if (in_array(session()->get('level'), ['Superadmin', 'kabupaten'])): ?>
                        <div id="boxOPDHapus" class="d-none mb-3">
                            <label class="small fw-bold">Pilih OPD</label>
                            <select name="id_opd_hapus" class="form-select form-select-sm border-danger select2-hapus">
                                <option value="">-- Pilih Dinas/Badan --</option>
                                <?php foreach($opd as $o): ?>
                                    <option value="<?= $o['id_opd'] ?>"><?= $o['nama_opd'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>

                    <div id="boxPegawaiHapus" class="d-none mb-3">
                        <label class="small fw-bold">Pilih Pegawai (Bisa Lebih Dari 1)</label>
                        <select name="target_pegawai_hapus[]" class="form-select form-select-sm border-danger select2-hapus-multiple" multiple="multiple">
                            <?php foreach($pegawai as $pg): ?>
                                <option value="<?= $pg['id_pegawai'] ?>"><?= $pg['nama_lengkap'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">Dari Tanggal</label>
                            <input type="date" name="tgl_mulai_hapus" class="form-control form-control-sm" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="small fw-bold">Sampai Tanggal</label>
                            <input type="date" name="tgl_selesai_hapus" class="form-control form-control-sm" required>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-danger w-100 rounded-pill fw-bold" onclick="return confirm('Apakah Anda yakin? Data jadwal yang dihapus tidak bisa dikembalikan.')">
                        MULAI HAPUS MASSAL
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // JS Logic untuk Radio Button Tipe Tanggal
    function toggleTipeTanggal() {
        const tipeRange = document.getElementById('tipeRange').checked;
        const boxRange = document.getElementById('boxRangeTanggal');
        const boxMulti = document.getElementById('boxMultiTanggal');
        
        if (tipeRange) {
            boxRange.classList.remove('d-none');
            boxMulti.classList.add('d-none');
            document.getElementById('flatpickr-multi').required = false; 
        } else {
            boxRange.classList.add('d-none');
            boxMulti.classList.remove('d-none');
            document.getElementById('flatpickr-multi').required = true;
        }
    }

    function toggleScopeHapus() {
        const val = document.getElementById('scopeHapus').value;
        const boxOPD = document.getElementById('boxOPDHapus');
        const boxPeg = document.getElementById('boxPegawaiHapus');

        if(boxOPD) boxOPD.classList.add('d-none');
        if(boxPeg) boxPeg.classList.add('d-none');

        if (val === 'opd' && boxOPD) boxOPD.classList.remove('d-none');
        if (val === 'pegawai' && boxPeg) boxPeg.classList.remove('d-none');
    }

    function toggleScope() {
        const boxGlobal = document.getElementById('boxGlobal');
        const boxOPD = document.getElementById('boxOPD');
        const boxPegawai = document.getElementById('boxPegawai');

        if(boxGlobal) boxGlobal.classList.add('d-none');
        if(boxOPD) boxOPD.classList.add('d-none');
        if(boxPegawai) boxPegawai.classList.add('d-none');

        if (document.getElementById('scopeGlobal').checked && boxGlobal) {
            boxGlobal.classList.remove('d-none');
        } else if (document.getElementById('scopeOPD') && document.getElementById('scopeOPD').checked && boxOPD) {
            boxOPD.classList.remove('d-none');
        } else if (document.getElementById('scopePegawai').checked && boxPegawai) {
            boxPegawai.classList.remove('d-none');
        }
    }
    
    // FUNGSI UNTUK HAPUS SATUAN DI DATATABLES
    function hapusPlotting(id) {
        Swal.fire({
            title: 'Hapus Jadwal?',
            text: "Data yang dihapus tidak dapat dikembalikan!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Hapus!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post("<?= base_url('plotting/hapus/') ?>" + id, { <?= csrf_token() ?>: "<?= csrf_hash() ?>" }, function(response) {
                    if (response.status === 'success') {
                        $('#tablePlotting').DataTable().ajax.reload(null, false);
                        Swal.fire({ icon: 'success', title: 'Berhasil!', text: response.message, timer: 1500, showConfirmButton: false });
                    }
                }, 'json');
            }
        });
    }
</script>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        // Init Select2 & Flatpickr
        $('.select2-manual').select2({ theme: 'bootstrap-5', dropdownParent: $('#modalPlot'), width: '100%' });
        $('.select2-massal').select2({ theme: 'bootstrap-5', dropdownParent: $('#modalPlotMassal'), width: '100%' });
        $('.select2-massal-multiple').select2({ theme: 'bootstrap-5', dropdownParent: $('#modalPlotMassal'), width: '100%', placeholder: '-- Pilih Beberapa Pegawai --', allowClear: true });
        $('.select2-hapus').select2({ theme: 'bootstrap-5', dropdownParent: $('#modalHapusMassal'), width: '100%' });
        $('.select2-hapus-multiple').select2({ theme: 'bootstrap-5', dropdownParent: $('#modalHapusMassal'), width: '100%', placeholder: '-- Pilih Beberapa Pegawai --', allowClear: true });
        
        flatpickr("#flatpickr-multi", {
            mode: "multiple",
            dateFormat: "Y-m-d",
            conjunction: ", "
        });

        // ==============================================
        // INISIALISASI DATATABLES SERVER-SIDE
        // ==============================================
        $('#tablePlotting').DataTable({
            processing: true,
            serverSide: true,
            order: [], 
            ajax: {
                url: "<?= base_url('plotting/ajax_list') ?>",
                type: "POST",
                data: function(d) {
                    d.<?= csrf_token() ?> = "<?= csrf_hash() ?>";
                }
            },
            language: {
                processing: '<div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status"><span class="visually-hidden">Memuat...</span></div><h6 class="mt-2 text-primary fw-bold">Memuat Data Plotting...</h6>',
                search: "Pencarian:",
                lengthMenu: "Tampilkan _MENU_ data",
                info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                infoEmpty: "Menampilkan 0 sampai 0 dari 0 data",
                infoFiltered: "(disaring dari _MAX_ total data)",
                paginate: {
                    first: "Awal",
                    last: "Akhir",
                    next: "Lanjut",
                    previous: "Mundur"
                }
            },
            columnDefs: [
                { targets: [3], orderable: false }
            ]
        });

        // ==============================================
        // AJAX SUBMIT FORMS
        // ==============================================
        
        // 1. AJAX SUBMIT - SIMPAN MANUAL
        $('#formSimpanManual').on('submit', function(e) {
            e.preventDefault();
            let formBtn = $(this).find('button[type="submit"]');
            formBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Menyimpan...');

            $.ajax({
                url: $(this).attr('action'),
                type: "POST",
                data: $(this).serialize(),
                dataType: "json",
                success: function(response) {
                    formBtn.prop('disabled', false).text('Simpan Jadwal');
                    if(response.status === 'success') {
                        $('#modalPlot').modal('hide');
                        $('#tablePlotting').DataTable().ajax.reload(null, false);
                        Swal.fire({ icon: 'success', title: 'Tersimpan!', text: response.message, timer: 2000, showConfirmButton: false });
                        $('#formSimpanManual')[0].reset();
                        $('.select2-manual').val(null).trigger('change');
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                },
                error: function() {
                    formBtn.prop('disabled', false).text('Simpan Jadwal');
                    Swal.fire('Error!', 'Terjadi kesalahan pada server', 'error');
                }
            });
        });

        // 2. AJAX SUBMIT - SIMPAN MASSAL
        $('#formSimpanMassal').on('submit', function(e) {
            e.preventDefault();
            
            Swal.fire({
                title: 'Memproses Data...',
                html: 'Mohon tunggu, sistem sedang membuat ribuan jadwal plotting. <b>Jangan tutup jendela ini.</b>',
                allowOutsideClick: false,
                didOpen: () => { Swal.showLoading(); }
            });

            $.ajax({
                url: $(this).attr('action'),
                type: "POST",
                data: $(this).serialize(),
                dataType: "json",
                success: function(response) {
                    if(response.status === 'success') {
                        $('#modalPlotMassal').modal('hide');
                        $('#tablePlotting').DataTable().ajax.reload(null, false);
                        Swal.fire('Berhasil!', response.message, 'success');
                    } else {
                        Swal.fire('Gagal!', response.message, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error!', 'Gagal menghubungi server.', 'error');
                }
            });
        });

        // 3. AJAX SUBMIT - HAPUS MASSAL
        $('#formHapusMassal').on('submit', function(e) {
            e.preventDefault();
            
            Swal.fire({
                title: 'Hapus Massal?',
                text: "Ribuan data jadwal akan dihapus secara permanen!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                confirmButtonText: 'Ya, Eksekusi!'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Menghapus Data...',
                        allowOutsideClick: false,
                        didOpen: () => { Swal.showLoading(); }
                    });

                    $.ajax({
                        url: $(this).attr('action'),
                        type: "POST",
                        data: $(this).serialize(),
                        dataType: "json",
                        success: function(response) {
                            if(response.status === 'success') {
                                $('#modalHapusMassal').modal('hide');
                                $('#tablePlotting').DataTable().ajax.reload(null, false);
                                Swal.fire('Berhasil!', response.message, 'success');
                            } else {
                                Swal.fire('Gagal!', response.message, 'error');
                            }
                        }
                    });
                }
            });
        });

    });
</script>

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