<?php $__env->startSection('content'); ?>
    <?php if($canCreate): ?>
        <?php if (isset($component)) { $__componentOriginald411d1792bd6cc877d687758b753742c = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginald411d1792bd6cc877d687758b753742c = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.primary-button','data' => ['dataBsToggle' => 'modal','dataBsTarget' => '#modalTambah','class' => 'mb-4']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('primary-button'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(Illuminate\View\AnonymousComponent::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['data-bs-toggle' => 'modal','data-bs-target' => '#modalTambah','class' => 'mb-4']); ?>Tambah
            Checklist <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginald411d1792bd6cc877d687758b753742c)): ?>
<?php $attributes = $__attributesOriginald411d1792bd6cc877d687758b753742c; ?>
<?php unset($__attributesOriginald411d1792bd6cc877d687758b753742c); ?>
<?php endif; ?>
<?php if (isset($__componentOriginald411d1792bd6cc877d687758b753742c)): ?>
<?php $component = $__componentOriginald411d1792bd6cc877d687758b753742c; ?>
<?php unset($__componentOriginald411d1792bd6cc877d687758b753742c); ?>
<?php endif; ?>
    <?php endif; ?>

    <div class="card shadow-sm border-0">
        <div class="card-header bg-white">
            <h6 class="mb-0 fw-bold">Filter Data</h6>
        </div>

        <div class="card-body">
            <form id="filterForm" class="row g-3 align-items-end">
                
                <div class="col-md-4">
                    <label for="location_id" class="form-label">Sites</label>
                    <select name="location_id" id="location_id" class="form-select">
                        <option value="all">- Pilih -</option>
                        <?php $__currentLoopData = $location; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $site): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($site->id); ?>"><?php echo e($site->name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                
                <div class="col-md-4">
                    <label for="shift_id" class="form-label">Shift</label>
                    <select name="shift_id" id="shift_id" class="form-select">
                        <option value="all">- Pilih -</option>
                        <?php $__currentLoopData = $shift; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($item->id); ?>"><?php echo e($item->name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                
                <div class="col-md-4">
                    <label for="tanggal" class="form-label">Tanggal</label>
                    <input type="date" id="tanggal" name="tanggal" class="form-control" value="<?php echo e(now()->format('Y-m-d')); ?>"
                        autocomplete="off">
                </div>

                
                <div class="col-12 d-flex gap-2 mt-3">
                    <button type="button" id="btnFilter" class="btn btn-primary">
                        <i class="fa fa-search me-1"></i> Cari
                    </button>

                    <button type="button" id="btnCetak" class="btn btn-info text-white">
                        <i class="fa fa-print me-1"></i> Cetak PDF
                    </button>

                    <button type="reset" id="btnReset" class="btn btn-light border">
                        <i class="fa fa-undo me-1"></i> Reset
                    </button>
                </div>
            </form>
        </div>
    </div>


    <div class="card">
        <div class="card-body">
            <table id="activeTable" class="table table-striped data-table">
                <thead>
                    <tr>
                        <th id="no">No</th>
                        <th>Code Report</th>
                        <th>Unit</th>
                        <th>Cheklist</th>
                        <th>Tanggal</th>
                        <th>Site</th>
                        <th>User</th>
                        <th>Shift</th>
                        <th>Status Checklist</th>
                        <th>Jumlah Item Rusak</th>
                        <th width="105px">Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>




    <?php echo $__env->make('daily.modal.add', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make('daily.modal.edit', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php $__env->stopSection(); ?>
<?php $__env->startPush('extraJS'); ?>
    <script>
        <?php if(session('success')): ?>
            Swal.fire({
                icon: 'success',
                title: 'Berhasil!',
                text: "<?php echo e(session('success')); ?>",
                timer: 2000,
                showConfirmButton: false
            });
        <?php endif; ?>

        <?php if(session('error')): ?>
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: "<?php echo e(session('error')); ?>",
            });
        <?php endif; ?>
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            let table;
            $(function () {
                table = $('#activeTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: "<?php echo e(route('daily-report.index')); ?>",
                        data: function (d) {
                            d.option = "active";
                            if ($('#location_id').val() !== 'all') {
                                d.location_id = $('#location_id').val();
                            }
                            if ($('#shift_id').val() !== 'all') {
                                d.shift_id = $('#shift_id').val();
                            }
                            if ($('#tanggal').val() !== 'all') {
                                d.tanggal = $('#tanggal').val();
                            }
                        },
                        error: function (e) {
                            console.log(e);
                        }
                    },
                    columnDefs: [{
                        width: "50px",
                        targets: 0
                    } // 0 adalah index kolom 'id'
                    ],
                    columns: [{
                        data: 'DT_RowIndex',
                        name: 'DT_RowIndex',
                        className: 'text-center',
                        orderable: false,
                        searchable: false
                    },
                    {
                        data: 'code_report',
                        name: 'code_report'
                    },
                    {
                        data: 'vehicle',
                        name: 'vehicle'
                    },
                    {
                        data: 'Checklist',
                        name: 'Checklist'
                    },
                    {
                        data: 'date',
                        name: 'date',
                        render: function (data, type, row) {
                            if (!data) return '-';

                            const d = new Date(data);
                            const pad = (n) => String(n).padStart(2, '0');

                            const day = pad(d.getDate());
                            const month = pad(d.getMonth() + 1);
                            const year = d.getFullYear();

                            const hours = pad(d.getHours());
                            const minutes = pad(d.getMinutes());
                            const seconds = pad(d.getSeconds());

                            return `${day} -${month} -${year} | ${hours}:${minutes}:${seconds}`;
                        }
                    },
                    {
                        data: 'location',
                        name: 'location'
                    },
                    {
                        data: 'user',
                        name: 'user'
                    },
                    {
                        data: 'shift',
                        name: 'shift',
                        render: function (data, type, row) {
                            return 'Shift - ' + data;
                        }
                    },
                    {
                        data: 'status_checklist',
                        name: 'status_checklist'
                    },
                    {
                        data: 'rusak_count',
                        name: 'rusak_count'
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        searchable: false
                    },
                    ]
                });

                $("#btnFilter").on("click", () => {
                    table.ajax.reload();
                })
            });

            $('#btnCetak').on('click', function (e) {
                e.preventDefault();

                let site_id = $('#location_id').val();
                let shift_id = $('#shift_id').val();
                let tanggal = $('#tanggal').val();

                if (!site_id || site_id == "all" || !shift_id || shift_id == "all") {
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Silakan pilih Sites dan Shift terlebih dahulu!',
                        confirmButtonColor: '#3085d6'
                    });
                    return;
                }

                Swal.fire({
                    title: 'Sedang menyiapkan file...',
                    text: 'Mohon tunggu sebentar',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                $.ajax({
                    url: "<?php echo e(route('daily-report.downloadAll')); ?>",
                    type: 'POST',
                    data: {
                        _token: "<?php echo e(csrf_token()); ?>",
                        site_id: site_id,
                        shift_id: shift_id,
                        tanggal: tanggal
                    },
                    xhrFields: {
                        responseType: 'blob' // supaya bisa handle file zip
                    },
                    success: function (data, status, xhr) {
                        Swal.close();
                        // ðŸ§  Cek apakah responsenya JSON error (bukan file)
                        const contentType = xhr.getResponseHeader('Content-Type');
                        console.log(xhr);
                        if (contentType && contentType.indexOf('application/json') !== -1) {
                            // Konversi blob ke JSON
                            const reader = new FileReader();
                            reader.onload = function () {
                                const json = JSON.parse(reader.result);
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Gagal!',
                                    text: json.error ||
                                        'Terjadi kesalahan tidak diketahui.'
                                });
                            };
                            reader.readAsText(data);
                            return;
                        }
                        let disposition = xhr.getResponseHeader('Content-Disposition');
                        let filename = `Laporan_PDF_${tanggal}.zip`; // default

                        if (disposition && disposition.indexOf('filename=') !== -1) {
                            let matches = disposition.match(
                                /filename[^;=\n]=((['"]).?\2|[^;\n]*)/);
                            if (matches != null && matches[1]) {
                                filename = matches[1].replace(/['"]/g, '');
                            }
                        }
                        // âœ… Kalau bukan JSON (berarti zip)
                        const blob = new Blob([data], {
                            type: 'application/zip'
                        });
                        const link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);
                        link.download = filename;
                        link.click();

                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: 'File ZIP berhasil didownload.',
                            confirmButtonColor: '#3085d6'
                        });
                    },
                    error: function (xhr) {

                        Swal.close();

                        // let message = 'Terjadi kesalahan saat membuat file ZIP.';
                        let message = xhr;
                        try {
                            const json = JSON.parse(xhr.responseText);
                            if (json.error) message = json.error;
                        } catch (e) { }

                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal!',
                            text: "Folder atau file tidak ada"
                        });
                    }
                });
            });


            // tambah
            // $('#formTambah').on('submit', function (e) {
            //     e.preventDefault();
            //     const form = $(this);
            //     const name = $('#name').val();
            //     if (!name) {
            //         Swal.fire({
            //             icon: 'warning',
            //             title: 'Validasi Gagal',
            //             text: 'shift wajib diisi.'
            //         });
            //         return;
            //     }

            //     $.ajax({
            //         url: '<?php echo e(route('daily-report.store')); ?>',
            //         method: 'POST',
            //         headers: {
            //             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            //         },
            //         data: form.serialize(),
            //         success: function (response) {
            //             $('#modalTambah').modal('hide');
            //             form.trigger("reset");

            //             Swal.fire({
            //                 icon: 'success',
            //                 title: 'Berhasil!',
            //                 text: response.message,
            //                 timer: 2000,
            //                 showConfirmButton: false
            //             });

            //             $('.data-table').DataTable().ajax.reload();
            //         },
            //         error: function (xhr) {
            //             let message = xhr.responseJSON?.message || 'Terjadi kesalahan';
            //             Swal.fire({
            //                 icon: 'error',
            //                 title: 'Gagal Menyimpan',
            //                 text: message
            //             });
            //         }
            //     });
            // });

            // edit
            $(document).on('click', '.edit', function () {
                let id = $(this).data('id');
                let name = $(this).data('name');
                let actions = $(this).data('actions');

                $('#edit-id').val(id);
                $('#edit-name').val(name);
                $('#modalEdit').modal('show');
            });

            $(document).on('click', '.pdf', function () {
                const id = $(this).data('id');


                Swal.fire({
                    icon: 'info',
                    title: 'Informasi',
                    text: "<?php echo e(session('success')); ?>",
                    showCancelButton: true,
                    showDenyButton: true,
                    confirmButtonText: 'Cetak Pdf',
                    denyButtonText: 'Preview',
                    cancelButtonText: 'Batal',
                }).then((result) => {
                    if (result.isConfirmed) {
                        const url = `<?php echo e(route('daily-report.show', ':id')); ?>`.replace(':id', id);

                        window.location.href = url;
                    } else if (result.isDenied) {
                        const url = `<?php echo e(route('daily-report.show', ':id')); ?>`.replace(':id', id) + '?isPreview=true';
                        window.open(url, '_blank'); // ubah URL sesuai kebutuhan
                    } else if (result.dismiss === Swal.DismissReason.cancel) {
                        // Aksi ketika tombol Batal ditekan
                        console.log('Aksi dibatalkan');
                    }
                });
            });

            // Handle form submit edit
            $('#formEdit').on('submit', function (e) {
                e.preventDefault();
                const form = $(this);

                let id = $('#edit-id').val();
                let name = $('#edit-name').val().trim();

                if (!name) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Validasi Gagal',
                        text: 'Nama shift wajib diisi.'
                    });
                    return;
                }

                $.ajax({
                    url: `<?php echo e(route('daily-report.update', ":id")); ?>`.replace(":id", id),
                    type: 'PUT',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: form.serialize(),
                    success: function (response) {
                        $('#modalEdit').modal('hide');

                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            timer: 2000,
                            showConfirmButton: false
                        });

                        $('.data-table').DataTable().ajax.reload();
                    },
                    error: function (xhr) {
                        let message = xhr.responseJSON?.message ||
                            'Terjadi kesalahan saat update.';
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal Update',
                            text: message
                        });
                    }
                });
            });
            // delete
            $(document).on("click", ".delete", function () {
                var id = $(this).data("id");

                Swal.fire({
                    title: 'Apakah kamu yakin?',
                    text: "Data akan dihapus secara permanen!",
                    icon: 'warning',
                    showCancelButton: true,
                    cancelButtonColor: '#3085d6',
                    confirmButtonColor: '#d33',
                    confirmButtonText: 'Ya, hapus!',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: `<?php echo e(route('daily-report.destroy', ":id")); ?>`.replace(":id", id),
                            type: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            },
                            success: function (res) {
                                Swal.fire('Terhapus!', res.message, 'success');
                                $('.data-table').DataTable().ajax.reload();
                            },
                            error: function (xhr) {
                                Swal.fire('Gagal!', 'Data gagal dihapus.', 'error');
                            }
                        });
                    }
                });
            });
            $('#btnFilter').on('click', function () {
                table.ajax.reload();
            });
        })
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('template.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/pmme2286/public_html/docu/vendor1/resources/views/daily/index.blade.php ENDPATH**/ ?>