<?= $this->extend('layout/template'); ?>
<?= $this->section('content'); ?>

<nav class="page-breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item">Laporan</li>
        <li class="breadcrumb-item active" aria-current="page">Laporan Data <?= $Breadcumb ?></li>
    </ol>
</nav>

<div class="d-flex align-items-center justify-content-between border p-3 rounded flex-wrap gap-3">
    <!-- Filter Tanggal -->
    <form id="filterForm" class="row mb-3">
        <div class="d-flex align-items-center gap-2 flex-wrap">

            <label for="tanggal" class="mb-0">Tanggal Awal</label>
            <div class="input-group flatpickr w-auto" id="flatpickr-date">
                <input type="text" name="tanggal_awal" class="form-control form-control-sm" placeholder="Pilih tanggal" data-input required>
                <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
            </div>

            <label for="tanggal" class="mb-0">Tanggal Akhir</label>
            <div class="input-group flatpickr w-auto" id="flatpickr-date">
                <input type="text" name="tanggal_akhir" class="form-control form-control-sm" placeholder="Pilih tanggal" data-input required>
                <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
            </div>
            <!-- Tombol Filter -->
            <!-- <button type="button" id="btnFilter" class="btn btn-primary btn-sm">
                <i data-feather="filter"></i> Filter
            </button> -->
        </div>
    </form>


    <!-- Tombol Export -->
    <div class="d-flex gap-2">
        <button type="button" class="btn btn-danger btn-sm" title="Export PDF" onclick="exportPDF()">
            <i class="icon-md" data-feather="file"></i> Print PDF
        </button>
        <button type="button" class="btn btn-success btn-sm" title="Export Excel" onclick="exportExcel()">
            <i class="icon-md" data-feather="file-text"></i> Excel Excel
        </button>
    </div>
</div>

<!-- Data Table -->
<div class="table-responsive">
    <table id="dataTableExample" class="table table-bordered table-hover">
        <thead class="table-info text-dark">
            <tr>
                <th style="width: 5%;">No</th>
                <th>Tanggal Pengajuan</th>
                <th>Nama Pegawai</th>
                <th>Jenis Cuti</th>
                <th>Tanggal Cuti</th>
                <th>Durasi</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $no = 1;
            $totalHari = 0;
            ?>
            <?php if (!empty($pengajuancuti)): ?>
                <?php foreach ($pengajuancuti as $row): ?>
                    <?php
                    $mulai = new DateTime($row['tanggal_mulai']);
                    $selesai = new DateTime($row['tanggal_selesai']);
                    $lamaCuti = $mulai->diff($selesai)->days + 1;
                    $totalHari += $lamaCuti;
                    ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= date('d M Y', strtotime($row['created_at'])) ?></td>
                        <td><?= esc($row['nama']) ?></td>
                        <td><?= esc($row['nama_jenis']) ?></td>
                        <td><?= date('d M Y', strtotime($row['tanggal_mulai'])) ?> s.d. <?= date('d M Y', strtotime($row['tanggal_selesai'])) ?></td>
                        <td><?= $lamaCuti ?> hari</td>
                        <td>
                            <?php if ($row['status_supervisor'] === 'disetujui' && $row['status_manager'] === 'disetujui'): ?>
                                <span class="badge bg-success">Disetujui</span>
                            <?php elseif ($row['status_supervisor'] === 'ditolak' || $row['status_manager'] === 'ditolak'): ?>
                                <span class="badge bg-danger">Ditolak</span>
                            <?php else: ?>
                                <span class="badge bg-warning text-dark">Diproses</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="7" class="text-center" style="background-color: #f9f9f9; color: #888; font-style: italic; padding: 20px;">
                        <i class="fas fa-folder-open" style="font-size: 24px; color: #ccc;"></i>
                        <br>
                        <span style="font-size: 16px; font-weight: bold;">Tidak ada data cuti yang tersedia.</span>
                        <br>
                        <span style="font-size: 14px;">Belum ada pengajuan cuti yang tercatat.</span>
                    </td>
                </tr>
            <?php endif; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5" class="text-right font-weight-bold">Total Hari Cuti</td>
                <td colspan="2"><strong><?= $totalHari ?> Hari</strong></td>
            </tr>
        </tfoot>
    </table>
</div>

<!-- filter laporan pengajuan cuti -->
<script>
    $(document).ready(function() {
        function loadData() {
            let tanggal_awal = $('input[name="tanggal_awal"]').val();
            let tanggal_akhir = $('input[name="tanggal_akhir"]').val();

            $.ajax({
                url: "<?= base_url('laporan/filterLaporanPengajuanCuti') ?>",
                type: "POST",
                data: {
                    tanggal_awal: tanggal_awal,
                    tanggal_akhir: tanggal_akhir
                },
                dataType: "json",
                success: function(response) {
                    let tbody = $("#dataTableExample tbody");
                    tbody.empty();

                    let totalHari = 0;

                    if (response.length > 0) {
                        $.each(response, function(index, row) {
                            let mulai = new Date(row.tanggal_mulai);
                            let selesai = new Date(row.tanggal_selesai);
                            let durasi = Math.floor((selesai - mulai) / (1000 * 60 * 60 * 24)) + 1;
                            totalHari += durasi;

                            let status = '';
                            if (row.status_supervisor === 'disetujui' && row.status_manager === 'disetujui') {
                                status = `<span class="badge bg-success">Disetujui</span>`;
                            } else if (row.status_supervisor === 'ditolak' || row.status_manager === 'ditolak') {
                                status = `<span class="badge bg-danger">Ditolak</span>`;
                            } else {
                                status = `<span class="badge bg-warning text-dark">Diproses</span>`;
                            }

                            let tr = `
                                <tr>
                                    <td>${index + 1}</td>
                                    <td>${new Date(row.created_at).toLocaleDateString('id-ID')}</td>
                                    <td>${row.nama}</td>
                                    <td>${row.nama_jenis}</td>
                                    <td>${new Date(row.tanggal_mulai).toLocaleDateString('id-ID')} s.d. ${new Date(row.tanggal_selesai).toLocaleDateString('id-ID')}</td>
                                    <td>${durasi} hari</td>
                                    <td>${status}</td>
                                </tr>
                            `;
                            tbody.append(tr);
                        });

                        $("#dataTableExample tfoot").html(`
                            <tr>
                                <td colspan="5" class="text-end font-weight-bold">Total Hari Cuti</td>
                                <td colspan="2"><strong>${totalHari} Hari</strong></td>
                            </tr>
                        `);
                    } else {
                        tbody.append(`
                            <tr>
                                <td colspan="7" class="text-center" style="font-style: italic; color: #888;">
                                    <i class="fas fa-folder-open" style="font-size: 24px; color: #ccc;"></i><br>
                                    Tidak ada data pengajuan cuti.
                                </td>
                            </tr>
                        `);
                        $("#dataTableExample tfoot").html('');
                    }
                },
                error: function(xhr, status, error) {
                    console.error("Error:", error);
                }
            });
        }

        // Trigger saat input tanggal berubah atau tombol diklik
        $('input[name="tanggal_awal"], input[name="tanggal_akhir"]').on("change", loadData);
        $('#btnFilter').on('click', loadData);

        // Load awal
        loadData();
    });
</script>



<!-- untuk script export pdf dan excel -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.3/xlsx.full.min.js"></script>

<script>
    function exportPDF() {
        const {
            jsPDF
        } = window.jspdf;
        let doc = new jsPDF('p', 'mm', 'a4');

        doc.setFont("helvetica", "bold");
        doc.setFontSize(16);
        doc.text("Laporan Pengajuan Cuti", 14, 15);

        let headers = [
            ["No", "Tgl Pengajuan", "Nama Pegawai", "Jenis Cuti", "Tgl Cuti", "Lama", "Status"]
        ];

        let data = [];
        $("#dataTableExample tbody tr:visible").each(function() {
            let row = [];
            row.push($(this).find("td:eq(0)").text().trim()); // No
            row.push($(this).find("td:eq(1)").text().trim()); // Tgl Pengajuan
            row.push($(this).find("td:eq(2)").text().trim()); // Nama
            row.push($(this).find("td:eq(3)").text().trim()); // Jenis
            row.push($(this).find("td:eq(4)").text().trim()); // Tgl Cuti
            row.push($(this).find("td:eq(5)").text().trim()); // Lama
            row.push($(this).find("td:eq(6)").text().trim()); // Status
            data.push(row);
        });

        // Total Hari
        let totalHari = $("#dataTableExample tfoot td:last").text().replace("Hari", "").trim();

        if (data.length === 0) {
            alert("Tidak ada data untuk diekspor!");
            return;
        }

        data.push(["", "", "", "", "Total", totalHari + " Hari", ""]);

        doc.autoTable({
            head: headers,
            body: data,
            startY: 25,
            styles: {
                fontSize: 10
            },
            theme: 'grid',
            headStyles: {
                fillColor: [22, 160, 133]
            },
            margin: {
                top: 30
            }
        });

        doc.save("Laporan_Pengajuan_Cuti.pdf");
    }

    function exportExcel() {
        if (typeof XLSX === 'undefined') {
            alert("XLSX tidak ditemukan!");
            return;
        }

        let ws = XLSX.utils.aoa_to_sheet([]);
        let headers = [
            ["No", "Tgl Pengajuan", "Nama Pegawai", "Jenis Cuti", "Tgl Cuti", "Lama", "Status"]
        ];
        XLSX.utils.sheet_add_aoa(ws, headers, {
            origin: "A1"
        });

        let data = [];
        $("#dataTableExample tbody tr:visible").each(function() {
            let row = [];
            row.push($(this).find("td:eq(0)").text().trim());
            row.push($(this).find("td:eq(1)").text().trim());
            row.push($(this).find("td:eq(2)").text().trim());
            row.push($(this).find("td:eq(3)").text().trim());
            row.push($(this).find("td:eq(4)").text().trim());
            row.push($(this).find("td:eq(5)").text().trim());
            row.push($(this).find("td:eq(6)").text().trim());
            data.push(row);
        });

        let totalHari = $("#dataTableExample tfoot td:last").text().replace("Hari", "").trim();

        if (data.length === 0) {
            alert("Tidak ada data untuk diekspor!");
            return;
        }

        data.push(["", "", "", "", "Total", totalHari + " Hari", ""]);
        XLSX.utils.sheet_add_aoa(ws, data, {
            origin: "A2"
        });

        let wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Laporan Cuti");
        XLSX.writeFile(wb, "Laporan_Pengajuan_Cuti.xlsx");
    }
</script>


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