@php
    $user_role = Auth::user()->role;
@endphp

@extends('app.app')

@section('title')
    Vehicles Trip Report
@endsection

@section('customcss')
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
        integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
@endsection

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="card">
                <div class="card-header">
                    <div class="row d-flex align-items-center">
                        <div class="col-3">
                            <p class="card-title text-bold mb-0">Vehicle Trip Report</p>
                        </div>
                        @if ($user_role == \App\Models\Users::ROLE_VENDOR || $user_role == \App\Models\Users::ROLE_ADMIN)
                            @can('vehicle.create')
                                <!-- <div class="col text-end">
                                                                            <button id="btnMdlNewVhc" class="btn btn-sm btn-danger">Add New Vehicle</button>
                                                                        </div> -->
                            @endcan

                            {{-- <div class="col-auto text-end ps-0">
                                <button class="btn btn-sm btn-danger">Upload</button>
                            </div> --}}
                        @endif
                        <div class="col-auto text-end ps-0">
                            <!-- <button class="btn btn-sm btn-danger">Download</button> -->
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <!-- filter -->
                    <div class="row g-3 align-items-end">

                        <div class="col-6 col-md-3 col-lg-2">
                            <div class="form-group">
                                <label class="form-label text-muted mb-1">From</label>
                                <input type="text" class="form-control" id="tgl0" value="{{ date('d-m-Y 00:00') }}">
                            </div>
                        </div>

                        <div class="col-6 col-md-3 col-lg-2">
                            <div class="form-group">
                                <label class="form-label text-muted mb-1">To</label>
                                <input type="text" class="form-control" id="tgl1" value="{{ date('d-m-Y 23:59') }}">
                            </div>
                        </div>

                        <div class="col-6 col-md-3 col-lg-2">
                            <div class="form-group">
                                <label class="form-label text-muted mb-1">License Plate</label>
                                <select name="license_plate" class="form-control" id="filterNopol">
                                    <option value="">-- All --</option>
                                    @foreach ($listNopol as $nopol)
                                        <option value="{{ $nopol->id }}">{{ $nopol->nopol1 }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="col-6 col-md-3 col-lg-2">
                            <div class="form-group">
                                <label class="form-label text-muted mb-1">Vehicle Category</label>
                                <select name="vehicle_type" class="form-control" id="vehicleType">
                                    <option value="">-- All --</option>
                                    @foreach ($vehicletype as $vehicletypes)
                                        <option value="{{ $vehicletypes->id }}">{{ $vehicletypes->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="col-6 col-md-3 col-lg-2">
                            <div class="form-group">
                                <label class="form-label text-muted mb-1">Pool</label>
                                <select name="poolcode" class="form-control" id="poolcode">
                                    <option value="">-- All --</option>
                                    @foreach ($listpool as $listpools)
                                        <option value="{{ $listpools->pool_code }}">{{ $listpools->pool_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="col-12 col-lg-2 d-flex gap-2 justify-content-lg-end">
                            <button class="btn btn-primary w-100 w-lg-auto" id="submitFilter">
                                <i class="fa fa-search me-1"></i> Submit
                            </button>
                            <button class="btn btn-danger w-100 w-lg-auto" id="btnDownloadReport">
                                <i class="fa fa-download me-1"></i> Download Report
                            </button>
                        </div>

                    </div>
                </div>
                <div class="table-responsive p-3">
                    <table id="tVehicleTrips" class="table table-hover dataTable w-100">
                        <thead>
                            <tr class="">
                                <th class="" hidden>Vehicle ID</th>
                                <th class="">License Plate Number</th>
                                <th class="">Dist. Cat.</th>
                                <th class="">Pool</th>
                                <th class="">Number of Trip</th>
                                <th class="">Total Mileage (km)</th>
                                <th class="">Trip #</th>
                                <th class="">Start</th>
                                <th class="">Finish</th>
                                <th class="">Duration</th>
                                <th class="">Start (km)</th>
                                <th class="">Finish (km)</th>
                                <th class="">Distance (km)</th>
                                <th class="">Fuel (L)</th>
                                <th class="">Vehicle Category</th>
                                <th class="">Detail</th>
                            </tr>
                        </thead>
                        <!-- <tbody>
                            <tr>
                             <td>24-679</td>
                             <td>24-679</td>
                             <td>26</td>
                             <td>442.3</td>
                            </tr>
                            <tr>
                             <td>24-682</td>
                             <td>24-682</td>
                             <td>28</td>
                             <td>312.7</td>
                            </tr>
                            <tr>
                             <td>24-877</td>
                             <td>24-877</td>
                             <td>15</td>
                             <td>276.4</td>
                            </tr>
                            <tr>
                             <td>A.16-347</td>
                             <td>A.16-347</td>
                             <td>37</td>
                             <td>543.2</td>
                            </tr>
                            <tr>
                             <td>AL2025-B21</td>
                             <td>AL2025-B21</td>
                             <td>18</td>
                             <td>295.4</td>
                            </tr>
                            <tr>
                             <td>B.16-542</td>
                             <td>B.16-542</td>
                             <td>32</td>
                             <td>478.2</td>
                            </tr>
                            <tr>
                             <td>B.24-264</td>
                             <td>B.24-264</td>
                             <td>24</td>
                             <td>188.4</td>
                            </tr>
                            <tr>
                             <td>B.24-274</td>
                             <td>B.24-274</td>
                             <td>33</td>
                             <td>440.1</td>
                            </tr>
                            <tr>
                             <td>Ford Ranger</td>
                             <td>26-199</td>
                             <td>30</td>
                             <td>631.4</td>
                            </tr>
                            <tr>
                             <td>Nissan AD</td>
                             <td>B.10-517</td>
                             <td>27</td>
                             <td>375.9</td>
                            </tr>
                            <tr>
                             <td>Triton</td>
                             <td>A.29-127</td>
                             <td>26</td>
                             <td>508.2</td>
                            </tr>
                                                </tbody> -->
                    </table>
                </div>
            </div>
        </div>
    </div>
    </div>

    <!-- modal -->
    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlDetailTrip"
        aria-labelledby="mdlDetailTripLabel" aria-hidden="true">
        <!-- <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="mdlDetailTripLabel">-----</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                    </div>
                                    <div class="modal-footer">
                                    </div>
                                </div>
                            </div> -->
    </div>
@endsection

@section('customjs')
    <script src="{{ asset('assets/js/load-image.all.min.js') }}"></script>
    <!-- DataTables Buttons + JSZip (for Excel export) -->
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"
        integrity="sha512-ozq8xQKq6urvuU6jNgkfqAmT7jKN2XumbrX1JiB3TnF7tI48DPI4Gy1GXKD/V3EExgAs1V+pRO7vwtS1LHg0Gw=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script> -->
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
        integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
    <script src="https://unpkg.com/leaflet-routing-machine@3.2.12/dist/leaflet-routing-machine.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="{{ asset('assets/vendor/printThis.js') }}"></script>

    <script>
        'use strict';
        const State = {
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            storage_lara: "{{ asset('storage') }}/",
            dvc_type: {
                built_in: "{{ \App\Models\Devices::TYPE_BUILT_IN }}",
                portable: "{{ \App\Models\Devices::TYPE_PORTABLE }}",
            },
        };

        const Wrapper = {
            activate: function() {
                Wrapper.init();
                Wrapper.event();
                // DTable.table = $('#tVehicleTrips').DataTable()
                // DTable.activate();
            },
            init: () => {
                $('#tgl0, #tgl1').datetimepicker({
                    format: 'd-m-Y H:i',
                    defaultTime: '00:00',
                    closeOnDateSelect: true,
                    // mask:true
                });

            },
            event: function() {
                $('#submitFilter').on('click', function() {
                    DTable.reload();
                });
                // Trigger export on external button click
                $('#btnDownloadReport').on('click', function() {
                    DTable.table.button('.buttons-excel').trigger();
                });

                // detail trip
                $('#tVehicleTrips').on('click', '.btnDetailTrip', function(e) {
                    e.preventDefault();
                    const vid = $(this).data('vid');
                    const tgl0 = $(this).data('tgl0');
                    const tgl1 = $(this).data('tgl1');
                    const nopol1 = $(this).data('nopol1');

                    // $("#mdlDetailTrip").load("{{ route('view_report_trip_detail') }}");
                    $('#mdlDetailTrip').empty().load("{{ route('view_report_trip_detail') }}",
                        `vid=${vid}&tgl0=${tgl0}&tgl1=${tgl1}&nopol1=${nopol1}`, () => {
                            $('#mdlDetailTrip').modal('show')
                        })

                });
            },
        };

        const DTable = {
            table: null,
            lastAjax: null, // keep track of the last ajax request
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // Abort the last request if it's still running
                if (DTable.lastAjax) {
                    DTable.lastAjax.abort();
                }
                if (DTable.table) {
                    // If table already exists → reload
                    DTable.table.ajax.reload();
                    return;
                }

                DTable.table = $('#tVehicleTrips').DataTable({
                    searching: false, // 🔹 remove search box
                    ordering: false, // 🔹 disable sorting for all columns
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: function(data, callback, settings) {
                        // Abort previous
                        if (DTable.lastAjax) {
                            DTable.lastAjax.abort();
                        }

                        // Fire new request
                        DTable.lastAjax = $.ajax({
                            url: `{{ route('api_report_vehicle_trips_list') }}?
								cptid=${AppState.current_company}
								&from_date=${moment($('#tgl0').val(), "DD-MM-YYYY HH:mm").unix()}
								&to_date=${moment($('#tgl1').val(), "DD-MM-YYYY HH:mm").unix()}
								&vid=${$('#filterNopol').val() || ''}
                                &vt=${$('#vehicleType').val() || ''}
                                &poolcode=${$('#poolcode').val() || ''}
							`,
                            type: 'GET',
                            success: function(json) {
                                callback(json);
                            },
                            error: function(xhr, status, error) {
                                if (status !== 'abort') {
                                    console.error("AJAX error:", error);
                                }
                            },
                            complete: function() {
                                DTable.lastAjax = null;
                            }
                        });
                    },
                    deferRender: true,
                    columns: [{
                            data: 'id',
                            visible: false
                        }, // vhc_id
                        {
                            data: 'nopol1',
                            className: 'text-start',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: "dc_code",
                            className: 'text-start'
                        },
                        {
                            data: "pool_code",
                            className: 'text-start'
                        },
                        {
                            data: "total_trip",
                            className: 'text-end'
                        },
                        {
                            data: "total_mileage",
                            className: 'text-end',
                            render: (data, type, row, meta) => parseFloat(data).toFixed(2)
                        },
                        {
                            data: "trip_id",
                            className: 'text-end'
                        },
                        {
                            data: 'start',
                            render: (data, type, row, meta) => {
                                // let addr = row
                                return `
									${moment.unix(data + AppState.TIMEFIX).format('DD MMM YYYY HH:mm:ss')}<br>
									${Helper.shortenText(decodeURIComponent(row.startLoc || 'address'), 255) || "-"}
								`;
                            }
                        },
                        {
                            data: 'finish',
                            render: (data, type, row, meta) => {
                                // let addr = row
                                return `
									${moment.unix(data + AppState.TIMEFIX).format('DD MMM YYYY HH:mm:ss')}<br>
									${Helper.shortenText(decodeURIComponent(row.finishLoc || 'address'), 255) || "-"}
								`;
                            }
                        },
                        {
                            className: 'text-start',
                            render: function(data, type, row, meta) {
                                const start = moment.unix(row.start);
                                const finish = moment.unix(row.finish);

                                // calculate duration
                                const diff = moment.duration(finish.diff(start));
                                const hours = Math.floor(diff.asHours());
                                const minutes = diff.minutes();

                                return `${hours}h ${minutes}m`;
                            }
                        },
                        {
                            data: 'startMileage',
                            className: 'text-end',
                            render: function(data, type, row, meta) {
                                return (data === null) ? '0' : parseFloat(data).toFixed(0);
                            }
                        },
                        {
                            data: 'finishMileage',
                            className: 'text-end',
                            render: function(data, type, row, meta) {
                                return (data === null) ? '0' : parseFloat(data).toFixed(0);
                            }
                        },
                        {
                            data: 'mileage',
                            className: 'text-end',
                            render: function(data, type, row, meta) {
                                // const mileage = (row.finishMileage !== null && row.startMileage !== null) ? (row.finishMileage - row.startMileage) : row.mileage;
                                return (parseFloat(data).toFixed(2));
                            }
                        },
                        {
                            data: 'fuel_consume',
                            className: 'text-end',
                            render: function(data, type, row, meta) {
                                // const mileage = (row.finishMileage !== null && row.startMileage !== null) ? (row.finishMileage - row.startMileage) : row.mileage;
                                return (parseFloat(data / 10).toFixed(1));
                            }
                        },
                        {
                            data: "type_name",
                            className: 'text-start'
                        },
                        {
                            // visible: false,
                            data: 'vhc_id',
                            className: 'text-center',
                            render: function(data, type, row, meta) {
                                let action = `
									<a href="#" class="text-decoration-none me-1 btnDetailTrip"
										data-vid="${data}" data-tgl0="${row.start}" data-tgl1="${row.finish}" data-nopol1="${row.nopol1}">
										<span class="icon ion-eye fz-16"></span>
									</a>
								`;
                                return action;
                            }
                        },
                    ],
                    paging: false,
                    drawCallback: function(settings) {
                        const api = this.api();
                        const rows = api.rows({
                            page: 'current'
                        }).nodes();
                        let last = null;

                        api.column(0, {
                                page: 'current'
                            }) // vhc_id col
                            .data()
                            .each(function(group, i) {
                                if (last !== group) {
                                    // count how many rows this vhc_id spans
                                    const rowspanCount = api
                                        .column(0, {
                                            page: 'current'
                                        })
                                        .data()
                                        .filter(function(d) {
                                            return d === group;
                                        }).length;

                                    // merge vhc_id
                                    $(rows).eq(i).find('td:eq(0)').attr('rowspan', rowspanCount);
                                    $(rows).eq(i).find('td:eq(1)').attr('rowspan', rowspanCount);
                                    $(rows).eq(i).find('td:eq(2)').attr('rowspan', rowspanCount);
                                    $(rows).eq(i).find('td:eq(3)').attr('rowspan', rowspanCount);
                                    $(rows).eq(i).find('td:eq(4)').attr('rowspan', rowspanCount);

                                    // $(rows).eq(i).find('td:eq(3)').attr('rowspan', rowspanCount);

                                    last = group;
                                } else {
                                    // remove duplicate cells
                                    $(rows).eq(i).find('td:eq(0)').remove();
                                    $(rows).eq(i).find('td:eq(0)').remove();
                                    $(rows).eq(i).find('td:eq(0)').remove();
                                    $(rows).eq(i).find('td:eq(0)').remove();
                                    $(rows).eq(i).find('td:eq(0)').remove();
                                    // $(rows).eq(i).find('td:eq(0)').remove();
                                }
                            });
                    },
                    buttons: [{
                        extend: 'excelHtml5',
                        title: () => {
                            return `
								Vehicle Trip Report -
								${moment($('#tgl0').val(), "DD-MM-YYYY HH:mm").format('DD MMM YYYY HH:mm')}
								to
								${moment($('#tgl1').val(), "DD-MM-YYYY HH:mm").format('DD MMM YYYY HH:mm')}`
                        },
                        className: 'd-none', // hide default button
                        exportOptions: {
                            columns: ':visible:not(:last-child)' //
                        }
                    }]
                });
            },
        };

        function safeVal(selector) {
            const val = $(selector).val();
            return (val === undefined || val === null || val === '') ? null : val;
        }

        async function convertImgHtmlToFile(imgHtml, imgWidth, imgHeight, mimeType, fileName) {
            return new Promise((resolve, reject) => {
                try {
                    let canvas = document.createElement("canvas")

                    // Draw image to canvas.
                    canvas.width = imgWidth
                    canvas.height = imgHeight
                    let ctx = canvas.getContext('2d')
                    ctx.drawImage(imgHtml, 0, 0)

                    // Convert canvas to ImageState.
                    let imageData = ctx.getImageData(0, 0, imgWidth, imgHeight)
                    // console.log(imageState.data.byteLength + ' bytes.')

                    // Convert canvas to Blob
                    canvas.toBlob((blob) => {
                        let newReader = new FileReader();
                        newReader.addEventListener('loadend', () => {
                            // Convert canvas to ArrayBuffer
                            let arrayBuffer = newReader.result
                            // console.log(arrayBuffer.byteLength + ' bytes.')

                            // Convert ArrayBuffer to Blob
                            // let blob = new Blob([arrayBuffer], {type: mimeType})

                            // Dispay Blob content in an Image.
                            // console.log(URL.createObjectURL(blob))

                            // Generate as file
                            let newFile = new File([arrayBuffer], fileName, {
                                type: mimeType,
                                lastModified: new Date(),
                                size: arrayBuffer.byteLength,
                            })
                            resolve(newFile)
                        });
                        newReader.readAsArrayBuffer(blob);
                    }, mimeType);
                } catch (e) {
                    reject(e.message)
                }
            });
        }

        Wrapper.activate();
    </script>
@endsection
