@extends('template.master')
{{-- modal --}}

{{-- modal --}}
@section('content')
    <div class="card">
        <div class="card-body">
            <table id="activeTable" class="table table-striped data-table">
                <thead>
                    <tr>
                        <th id="no">No</th>
                        <th>Vehicle</th>
                        <th>Code Unit</th>
                        <th>Jumlah Cheklist</th>
                        <th>Hours meter</th>
                        <th width="105px">Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>

    @include('monthly.modal.add')
@endsection
@push('extraJS')
    <script>
        @if (session('success'))
            Swal.fire({
                icon: 'success',
                title: 'Berhasil!',
                text: "{{ session('success') }}",
                timer: 2000,
                showConfirmButton: false
            });
        @endif

        @if (session('error'))
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: "{{ session('error') }}",
            });
        @endif
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(function () {
                var table = $('#activeTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: "{{ route('monthly-report.index') }}",
                        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: 'vehicle',
                        name: 'vehicle',
                        searchable: true

                    },
                    {
                        data: 'unit_code',
                        name: 'unit_code'
                    },
                    {
                        data: 'jumlah_checklist',
                        name: 'jumlah_checklist'
                    },
                    {
                        data: 'hours_meter',
                        name: 'hours_meter'
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        // searchable: false
                    },
                    ]
                });

            });
            $(document).on("click", ".print", function () {
                $("#modal").modal("show")
                const unitId = $(this).data("id");
                $("#modal").find("[name='unitId']").val(unitId)
            })
            $('#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: "{{ route('daily-report.downloadAll') }}",
                    type: 'POST',
                    data: {
                        _token: "{{ 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"
                        });
                    }
                });
            });

        })
    </script>
@endpush
