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

@extends('app.app')

@section('title')
    Vehicles
@endsection

@section('customcss')
@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">Abnormality 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 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 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">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-4 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="">Vehicle ID</th> -->
                                <!-- <th class="text-center">Action</th> -->
                                <!-- <th class="">Vehicle Name</th> -->
                                <th class="">License Plate Number</th>
                                <th class="">Dist. Cat.</th>
                                <th class="">Pool</th>
                                <th class="">Time</th>
                                <th class="">Speed (kph)</th>
                                <th class="">Location</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
    </div>

    <!-- modal -->
@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>
        '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.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();
                });
            },
        };

        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,
                    ajax: function(data, callback, settings) {
                        // Abort previous
                        if (DTable.lastAjax) {
                            DTable.lastAjax.abort();
                        }

                        // Fire new request
                        DTable.lastAjax = $.ajax({
                            url: `{{ route('api_report_abnormalities_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() || ''}
                                &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: 'name',
                        // 	className: 'text-start text-nowrap',
                        // },
                        {
                            data: 'nopol1',
                            className: 'text-start',
                        },
                        {
                            data: 'dc_code',
                            className: 'text-start',
                        },
                        {
                            data: 'pool_code',
                            className: 'text-start',
                        },
                        {
                            data: "crt_d",
                            className: 'text-nowrap',
                            render: (data, type, row, meta) => {
                                return moment.unix(data + AppState.TIMEFIX).format(
                                    'DD MMM YYYY HH:mm:ss');
                            }
                        },
                        {
                            data: "speed",
                            className: 'text-end'
                        },
                        {
                            data: "fulladdress",
                            render: (data, type, row, meta) => {
                                return Helper.shortenText(decodeURIComponent(data || ''), 255)
                            },
                        },
                    ],
                    paging: false,
                    buttons: [{
                        extend: 'excelHtml5',
                        title: () => {
                            return `
								Abnormality 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(:first-child)' // 🔹 exclude first column
                        }
                    }]
                });
            },
        };

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

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