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

@extends('app.app')

@section('title')
    Drivers
@endsection

@section('customcss')
    <style>
        /* .select2-container {
                                                                                                                                                                                                                                                                                                                                                    z-index: 99999;
                                                                                                                                                                                                                                                                                                                                                } */
    </style>
@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">List Driver</p>
                        </div>
                        {{-- @if ($user_role === \App\Models\Users::ROLE_VENDOR) --}}
                        @if ($user_role === \App\Models\Users::ROLE_ADMIN)
                            @can('driver.create')
                                <div class="col text-end">
                                    <button id="btnMdlNewDrv" class="btn btn-sm btn-danger">Add New Driver</button>
                                </div>
                            @endcan
                        @endif
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="tDrivers" class="table table-hover dataTable">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center">Action</th>
                                    <th class="">Driver</th>
                                    {{-- <th class="">
                                        <div class="text-nowrap">Mileage<span class="text-lowercase d-block">(km)</span>
                                        </div>
                                        <span id="mileageSumMonth" class="text-capitalize">jan-2022</span>
                                    </th> --}}
                                    <th class="">Identification Number</th>
                                    <th class="">License Number</th>
                                    <th class="">License Expiry</th>
                                    <th class="">D<span class="text-lowercase">o</span>B</th> <!-- Date of Birth -->
                                    <th class="">Age</th>
                                    <th class="">Blood Type</th>
                                    <th class="">Phone Number</th>
                                    <th class="">Email Address</th>
                                    <th class="">Company</th>
                                    {{-- <th class="text-nowrap">Home Address</th> --}}
                                    {{-- <th class="">Emergency <span class="text-nowrap">Contact Name</span></th> --}}
                                    {{-- <th class="">Emergency <span class="text-nowrap">Contact Number</span> --}}
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                {{-- <tr class="">
                                    <td class="">1</td>
                                    <td class="text-nowrap">
                                        <span class="text-bold">Gülşen Makena Aarne</span>
                                    </td>
                                    <td class="">0</td>
                                    <td class="">KTP 3174011512880001</td>
                                    <td class="">NPWP 3174011512880004</td>
                                    <td class="text-nowrap">3174011512880078</td>
                                    <td class="text-nowrap">Jan 22, 2026</td>
                                    <td class="text-nowrap">Jan 22, 1988</td>
                                    <td class="text-end">34</td>
                                    <td class="">AB</td>
                                    <td class="text-nowrap">+62812 9283 8191</td>
                                    <td class="">gulsen.makena@aarne.com</td>
                                    <td class="">Jl. H Kavling No.20, RT.10/RW.9, Tebet Timur - Tebet, Jakarta
                                        Selatan, 13630</td>
                                    <td class="">
                                        WIFE <br>
                                        <span class="text-nowrap">Bridgette Gamila Bhavana</span>
                                    </td>
                                    <td class="text-nowrap">+62812 9283 8192</td>
                                    <td class="text-center">
                                        <a href="#" class="text-decoration-none me-1">
                                            <span class="icon ion-edit fz-16"></span>
                                        </a>
                                        <a href="#" class="text-decoration-none text-danger">
                                            <span class="icon ion-trash-b fz-16"></span>
                                        </a>
                                    </td>
                                </tr> --}}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlNewDrv" aria-labelledby="mdlNewDrvLabel" 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="mdlNewDrvLabel">New Driver</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        {{-- Personal Data --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Personal Data</h6>
                            </div>
                            <div class="row mb-3">
                                <div class="col-5">
                                    <label for="add-ktp-img" class="col-form-label">National ID Photo</label>
                                    <br>
                                    <img id="add-ktp-img" class="img-fluid landscape-photo" src="https://media.istockphoto.com/id/2181547993/video/id-card-verification-animation-accepted-and-decline-options.jpg?s=640x640&k=20&c=SI_5swuzBG578HTCL888NPLxpXMI0qM3kI1Br58vIG4=" alt="add-ktp-img">
                                    <div id="add-group_rotate_ktp" class="pt-2 d-flex justify-content-start d-none">
                                        <button type="button" class="btnRotateLeft btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-left"></i></button>
                                        <button type="button" class="btnRotateRight btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-right"></i></button>
                                    </div>
                                    <div id="add-group_ktp_spinner" class="d-none">
                                        <div class="spinner-border" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </div>
                                    <input type="file" id="add-ktp-file" class="form-control mt-3">
                                    <input type="text" id="add-ktp-base64" class="form-control" hidden>
                                    <div>
                                        <span id="add-ktp-status"></span>
                                        <span id="add-ktp-filesize"></span>
                                    </div>
                                </div>
                                <div class="col-7">
                                    <div class="row">
                                        <div class="col-6">
                                            <div class="mb-0">
                                                <label for="add-nik" class="col-form-label">ID Number</label>
                                                <input type="text" id="add-nik" class="form-control">
                                            </div>
                                            <div class="mb-0">
                                                <label for="add-dob" class="col-form-label">Date of Birth</label>
                                                <input type="text" id="add-dob" class="form-control" readonly>
                                            </div>
                                            <div class="mb-0">
                                                <label for="add-email" class="col-form-label">Email</label>
                                                <input type="email" id="add-email" class="form-control">
                                            </div>
                                        </div>

                                        <div class="col-6">
                                            <div class="mb-0">
                                                <label for="add-fullname" class="col-form-label">Fullname<span class="text-danger">*</span></label>
                                                <input type="text" id="add-fullname" class="form-control">
                                            </div>
                                            <div class="mb-0">
                                                <label for="add-blood" class="col-form-label">Blood Type</label>
                                                <select id="add-blood" class="form-control" style="width:100%;">
                                                    <option value="">Choose</option>
                                                    @foreach ($bloods as $blood)
                                                        <option value="{{ $blood['id'] }}">{{ $blood['name'] }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="mb-0">
                                                <label for="add-phone" class="col-form-label">Phone Number<span class="text-danger">*</span></label>
                                                <input type="number" id="add-phone" class="form-control" placeholder="without zero">
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <label for="add-fulladdress" class="col-form-label w-100">Home Address</label>
                                            <textarea id="add-fulladdress" class="form-control"></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- License Data --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>License Data</h6>
                            </div>
                            <div class="row">
                                <div class="col-5">
                                    <label for="add-license-img" class="col-form-label">License Photo</label>
                                    <br>
                                    <img id="add-license-img" class="img-fluid landscape-photo" src="https://s2.bukalapak.com/bukalapak-kontenz-production/content_attachments/50232/w-740/SIM_C1.jpg" alt="add-license-img">
                                    <div id="add-group_license_spinner" class="d-none">
                                        <div class="spinner-border" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </div>
                                    <div id="add-group_rotate_license" class="pt-2 d-flex justify-content-start d-none">
                                        <button type="button" class="btnRotateLeft btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-left"></i></button>
                                        <button type="button" class="btnRotateRight btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-right"></i></button>
                                    </div>
                                    <input type="file" id="add-license-file" class="form-control mt-3">
                                    <input type="text" id="add-license-base64" class="form-control" hidden>
                                    <div>
                                        <span id="add-license-status"></span>
                                        <span id="add-license-filesize"></span>
                                    </div>
                                </div>
                                <div class="col-7">
                                    <div class="mb-0">
                                        <label for="add-license-no" class="col-form-label">License Number</label>
                                        <input type="number" id="add-license-no" class="form-control">
                                    </div>
                                    <div class="mb-0">
                                        <label for="add-license-exp" class="col-form-label">License Expired</label>
                                        <input type="text" id="add-license-exp" class="form-control" readonly>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Emergency Data --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Emergency Data</h6>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <div class="mb-0">
                                        <label for="add-em-fullname" class="col-form-label">Emergency
                                            Contact Fullname</label>
                                        <input type="text" id="add-em-fullname" class="form-control">
                                    </div>
                                    <div class="mb-0">
                                        <label for="add-em-relationship" class="col-form-label">Emergency
                                            Contact Relationship</label>
                                        <select id="add-em-relationship" class="form-control" style="width:100%;">
                                            <option value="">Choose</option>
                                            @foreach ($relationships as $relation)
                                                <option value="{{ $relation['id'] }}">{{ $relation['name'] }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="mb-0">
                                        <label for="add-em-phone" class="col-form-label">Emergency
                                            Contact Number</label>
                                        <input type="number" id="add-em-phone" class="form-control" placeholder="without zero">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitNewDrv" type="button" class="btn btn-sm btn-danger">Submit data</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlEdtDrv" aria-labelledby="mdlEdtDrvLabel" 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="mdlEdtDrvLabel">Edit Driver</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        {{-- Personal Data --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Personal Data</h6>
                            </div>
                            <div class="row mb-3">
                                <div class="col-5">
                                    <label for="edt-ktp-img" class="col-form-label">National ID Photo</label>
                                    <br>
                                    <img id="edt-ktp-img" class="img-fluid landscape-photo" src="https://picture-origin.rumah123.com/news-content/img/2020/09/21080044/cara-mengurus-ktp-1.jpg" alt="edt-ktp-img">
                                    <div id="edt-group_ktp_spinner" class="d-none">
                                        <div class="spinner-border" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </div>
                                    <div id="edt-group_rotate_ktp" class="pt-2 d-flex justify-content-start d-none">
                                        <button type="button" class="btnRotateLeft btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-left"></i></button>
                                        <button type="button" class="btnRotateRight btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-right"></i></button>
                                    </div>
                                    <input type="file" id="edt-ktp-file" class="form-control mt-3">
                                    <input type="text" id="edt-ktp-base64" class="form-control" hidden>
                                    <div>
                                        <span id="edt-ktp-status"></span>
                                        <span id="edt-ktp-filesize"></span>
                                    </div>
                                </div>
                                <div class="col-7">
                                    <div class="row">
                                        <div class="col-6">
                                            <div class="mb-0">
                                                <label for="edt-nik" class="col-form-label">ID Number</label>
                                                <input type="text" id="edt-nik" class="form-control">
                                            </div>
                                            <div class="mb-0">
                                                <label for="edt-dob" class="col-form-label">Date of Birth</label>
                                                <input type="text" id="edt-dob" class="form-control" readonly>
                                            </div>
                                            <div class="mb-0">
                                                <label for="edt-email" class="col-form-label">Email</label>
                                                <input type="email" id="edt-email" class="form-control">
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="mb-0">
                                                <label for="edt-fullname" class="col-form-label">Fullname<span class="text-danger">*</span></label>
                                                <input type="text" id="edt-fullname" class="form-control">
                                            </div>
                                            <div class="col-6">
                                                <label for="edt-blood" class="col-form-label">Blood Type</label>
                                                <select id="edt-blood" class="form-control" style="width:100%;">
                                                    <option value="">Choose</option>
                                                    @foreach ($bloods as $blood)
                                                        <option value="{{ $blood['id'] }}">{{ $blood['name'] }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="mb-0">
                                                <label for="edt-phone" class="col-form-label">Phone Number<span class="text-danger">*</span></label>
                                                <input type="number" id="edt-phone" class="form-control" placeholder="without zero">
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <label for="edt-fulladdress" class="col-form-label">Home Address</label>
                                            <textarea id="edt-fulladdress" class="form-control"></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- License Data --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>License Data</h6>
                            </div>
                            <div class="row">
                                <div class="col-5">
                                    <label for="edt-license-img" class="col-form-label">License Photo</label>
                                    <br>
                                    <img id="edt-license-img" class="img-fluid landscape-photo" src="https://s2.bukalapak.com/bukalapak-kontenz-production/content_attachments/50232/w-740/SIM_C1.jpg" alt="edt-license-img">
                                    <div id="edt-group_license_spinner" class="d-none">
                                        <div class="spinner-border" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </div>
                                    <div id="edt-group_rotate_license" class="pt-2 d-flex justify-content-start d-none">
                                        <button type="button" class="btnRotateLeft btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-left"></i></button>
                                        <button type="button" class="btnRotateRight btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-right"></i></button>
                                    </div>
                                    <input type="file" id="edt-license-file" class="form-control mt-3">
                                    <input type="text" id="edt-license-base64" class="form-control" hidden>
                                    <div>
                                        <span id="edt-license-status"></span>
                                        <span id="edt-license-filesize"></span>
                                    </div>
                                </div>
                                <div class="col-7">
                                    <div class="m-0">
                                        <label for="edt-license-no" class="col-form-label">LicenseNumber</label>
                                        <input type="number" id="edt-license-no" class="form-control">
                                    </div>
                                    <div class="mb-0">
                                        <label for="edt-license-exp" class="col-form-label">LicenseExpired</label>
                                        <input type="text" id="edt-license-exp" class="form-control" readonly>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{-- Emergency Data --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Emergency Data</h6>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <label for="edt-em-fullname" class="col-form-label">Emergency
                                        Contact Fullname</label>
                                    <input type="text" id="edt-em-fullname" class="form-control">
                                </div>
                                <div class="col-12">
                                    <label for="edt-em-relationship" class="col-form-label">Emergency
                                        Contact Relationship</label>
                                    <select id="edt-em-relationship" class="form-control" style="width:100%;">
                                        <option value="">Choose</option>
                                        @foreach ($relationships as $relation)
                                            <option value="{{ $relation['id'] }}">{{ $relation['name'] }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label for="edt-em-phone" class="col-form-label">Emergency
                                        Contact Number</label>
                                    <input type="number" id="edt-em-phone" class="form-control" placeholder="without zero">
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer d-block">
                    <div class="row p-0">
                        {{-- <div class="col p-0 text-start">
                            <button type="button" id="btnResetLogin_updt" class="btn btn-sm btn-dark text-white">Reset Login ?</button>
                        </div> --}}
                        <div class="col p-0 text-end">
                            @can('driver.delete')
                                <button type="button" id="btnDelDrv_updt" class="btn btn-sm btn-warning">Delete ?</button>
                            @endcan
                            @can('driver.edit')
                                <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                            @endcan
                            <button id="btnSubmitEdtDrv" type="button" class="btn btn-sm btn-danger">Update data</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlDelDrv" aria-labelledby="mdlDelDrvLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlDelDrvLabel">Delete Driver</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-center">
                        <p class="mb-0">
                            Are you sure want to delete this driver
                            <a href="#" class="text-danger">
                                <span id="del-fullname"></span>
                                (<span id="del-phone"></span>)
                            </a>
                        </p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-danger" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitDelDrv" type="button" class="btn btn-sm btn-secondary">Yes, delete</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('customjs')
    <script src="{{ asset('assets/js/load-image.all.min.js') }}"></script>
    <script>
        'use strict';
        const State = {
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            storage_lara: "{{ asset('storage') }}/",
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                DNew.activate();
                DUpdate.activate();
                DDel.activate();
                Filter.activate();
                // new images
                DUploadAdd.activate('ktp');
                DUploadAdd.activate('npwp');
                DUploadAdd.activate('license');
                // update images
                DUploadEdt.activate('ktp');
                DUploadEdt.activate('npwp');
                DUploadEdt.activate('license');
                LoginDriver.activate();
            },
            event: function() {
                $('#mileageSumMonth').text(moment().format('MMM-YYYY'));

                $('#add-blood').select2({
                    dropdownParent: $('#mdlNewDrv'),
                });
                $('#add-em-relationship').select2({
                    dropdownParent: $('#mdlNewDrv'),
                });
                $('#add-vendor_id').select2({
                    dropdownParent: $('#mdlNewDrv'),
                });
                $('#add-bank').select2({
                    dropdownParent: $('#mdlNewDrv'),
                });

                $('#edt-blood').select2({
                    dropdownParent: $('#mdlEdtDrv'),
                });
                $('#edt-em-relationship').select2({
                    dropdownParent: $('#mdlEdtDrv'),
                });
                $('#edt-vendor_id').select2({
                    dropdownParent: $('#mdlEdtDrv'),
                });
                $('#edt-bank').select2({
                    dropdownParent: $('#mdlEdtDrv'),
                });
            },
        };

        const DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tDrivers').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                $('#tDrivers').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    // fixedColumns:   {
                    //     left: 3,
                    // },
                    ajax: {
                        url: "{{ route('api_list_drivers') }}?cptid=" + AppState.current_company,
                        type: 'GET',
                        complete: function() {
                            // removeTableSkeletonLoading()
                        },
                    },
                    deferRender: true,
                    columns: [{
                            data: 'DT_RowIndex',
                            className: 'text-end',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'action',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let action = `
									<a href="#" class="text-decoration-none me-1 btnEdtDrv">
										<span class="icon ion-eye fz-16"></span>
									</a>
								`;
                                // <a href="#" class="text-decoration-none text-danger btnDelDrv">
                                //     <span class="icon ion-trash-b fz-16"></span>
                                // </a>
                                return action;
                            }
                        },
                        {
                            data: 'fullname',
                            className: 'text-start',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-did', rowData.id);
                                $(td).attr('data-fullname', rowData.fullname);
                                $(td).attr('data-phone', rowData.phone);
                                $(td).attr('data-phone_code', rowData.phone_code);
                            },
                        },
                        // {
                        //     data: 'mileage_km',
                        //     className: 'text-end',
                        //     visible: true,
                        //     orderable: true,
                        //     searchable: true,
                        // },
                        {
                            data: 'nik',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let nik = Helper.splitEvery4Char(`${data}`);
                                return `
                                    <img src="${State.storage_lara}${row.ktp_img}" class="img-fluid thumb-img-table" />
                                    <br>${nik}
                                `;
                            },
                        },
                        // {
                        //     data: 'npwp_string',
                        //     className: 'text-start text-nowrap',
                        //     visible: true,
                        //     orderable: true,
                        //     searchable: true,
                        //     render: function(data, type, row, meta) {
                        //         return `
                    //         <img src="${State.storage_lara}${row.npwp_img}" class="img-fluid thumb-img-table" />
                    //         <br>${data}
                    //     `;
                        //     },
                        // },
                        {
                            data: 'license_number',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let license_number = Helper.splitEvery4Char(`${data}`);
                                return `
                                    <img src="${State.storage_lara}${row.license_img}" class="img-fluid thumb-img-table" />
                                    <br>${license_number}
                                `;
                            },
                        },
                        {
                            data: 'license_exp',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                // return data.split('-').reverse().join('-');
                                return moment(data).format('DD MMM YYYY');
                            },
                        },
                        {
                            data: 'dob',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                // return data.split('-').reverse().join('-');
                                return moment(data).format('DD MMM YYYY');
                            },
                        },
                        {
                            data: 'age',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'blood',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'phone',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (
                                    `<a href="tel:0${data}"><i class="text-dark ion-ios-telephone"></i> ${Helper.splitEvery4Char('0'+data)}</a>` +
                                    `<br>` +
                                    `<a href="https://api.whatsapp.com/send/?phone=62${data}&text=Halo&app_absent=0" target="_blank"><i class="text-success ion-social-whatsapp"></i> ${Helper.splitEvery4Char('0'+data)}</a>`
                                );
                            },
                        },
                        {
                            data: 'email',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        // {
                        //     data: 'fulladdress',
                        //     className: 'text-start',
                        //     visible: true,
                        //     orderable: true,
                        //     searchable: true,
                        // },
                        // {
                        //     data: 'em_fullname',
                        //     className: 'text-start text-nowrap',
                        //     visible: true,
                        //     orderable: true,
                        //     searchable: true,
                        //     render: function(data, type, row, meta) {
                        //         return `${data} - ${row.em_relationship}`;
                        //     },
                        // },
                        // {
                        //     data: 'em_phone',
                        //     className: 'text-end text-nowrap',
                        //     visible: true,
                        //     orderable: true,
                        //     searchable: true,
                        //     render: function(data, type, row, meta) {
                        //         return ('+' + row.em_phone_code + ' ' + Helper.splitEvery4Char(
                        //             `${data}`));
                        //     },
                        // },
                        {
                            data: 'company_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                    ],
                });
            },
        };

        const DNew = {
            activate: function() {
                DNew.event();
            },
            event: function() {
                // modal
                $('#btnMdlNewDrv').on('click', function() {
                    $('#mdlNewDrv').modal('show');
                });
                $('#mdlNewDrv').on('shown.bs.modal', function() {

                });
                $('#btnSubmitNewDrv').on('click', function() {
                    let data = DNew.getData();
                    DNew.submitData(data);
                });
                // datepicker
                $('#add-dob').datepicker({
                    format: 'dd-mm-yyyy',
                    startDate: moment().subtract(80, 'years').toDate(),
                    endDate: moment().subtract(17, 'years').toDate(),
                });
                $('#add-license-exp').datepicker({
                    format: 'dd-mm-yyyy',
                    startDate: moment().add(1, 'days').toDate(),
                });
                // file
                $('#add-ktp-file').on('click', function() {
                    $('#add-ktp-file').val('');
                });
                $('#add-npwp-file').on('click', function() {
                    $('#add-npwp-file').val('');
                });
                $('#add-license-file').on('click', function() {
                    $('#add-license-file').val('');
                });
            },
            getData: function() {
                let data = {};
                data.ktp_base64 = $('#add-ktp-base64').val().replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
                data.nik = $('#add-nik').val();
                data.fullname = $('#add-fullname').val();
                data.phone = $('#add-phone').val();
                data.email = $('#add-email').val();
                data.dob = $('#add-dob').val().split('-').reverse().join('-');
                data.age = moment().diff(moment(data.dob), 'years', false) || null;
                data.blood = $('#add-blood').val();
                data.fulladdress = $('#add-fulladdress').val();

                data.license_base64 = $('#add-license-base64').val().replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
                data.license_number = $('#add-license-no').val();
                data.license_exp = $('#add-license-exp').val().split('-').reverse().join('-');

                data.em_fullname = $('#add-em-fullname').val();
                data.em_relationship = $('#add-em-relationship').val();
                data.em_phone = $('#add-em-phone').val();

                data.vendor_id = $('#add-vendor_id').val();
                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitNewDrv').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitNewDrv').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_add_driver') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitNewDrv').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success add new driver');
                            $('#mdlNewDrv').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitNewDrv').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                })
            },
        }

        const DUpdate = {
            activate: function() {
                DUpdate.event();
            },
            event: function() {
                // modal
                $('#tDrivers').on('click', '.btnEdtDrv', async function(e) {
                    let did = $(e.target).closest('tr').find('td[data-did]').data('did');
                    let resp = await DUpdate.reqData({
                        did
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Driver Not Found', 'just now', 'please try again');
                        return false;
                    }
                    DUpdate.passDataToView(resp.data);
                });
                $('#mdlEdtDrv').on('shown.bs.modal', function() {

                });
                $('#btnSubmitEdtDrv').on('click', function() {
                    let data = DUpdate.getData();
                    DUpdate.submitData(data);
                });
                // datepicker
                $('#edt-dob').datepicker({
                    format: 'dd-mm-yyyy',
                    startDate: moment().subtract(80, 'years').toDate(),
                    endDate: moment().subtract(17, 'years').toDate(),
                });
                $('#edt-license-exp').datepicker({
                    format: 'dd-mm-yyyy',
                    startDate: moment().add(1, 'days').toDate(),
                });
                // file
                $('#edt-ktp-file').on('click', function() {
                    $('#edt-ktp-file').val('');
                });
                $('#edt-npwp-file').on('click', function() {
                    $('#edt-npwp-file').val('');
                });
                $('#edt-license-file').on('click', function() {
                    $('#edt-license-file').val('');
                });
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_show_driver', '') }}/" + params.did,
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        data: params,
                        success: (data, textStatus, jqXHR) => {
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                data: data.data
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                });
            },
            passDataToView: function(data) {
                $('#edt-ktp-filesize').html('');
                $('#edt-ktp-status').html('');
                $('#edt-ktp-base64').val('');
                $('#edt-ktp-file').val('');
                $('#edt-ktp-img').attr('src', State.storage_lara + data?.ktp_img);

                $('#edt-nik').val(data?.nik);
                $('#edt-fullname').val(data?.fullname);
                $('#edt-fullname2').val(data?.fullname2);
                $('#edt-phone').val(data?.phone);
                $('#edt-phone2').val(data?.phone2);
                $('#edt-email').val(data?.email);
                $('#edt-dob').val(data?.dob?.split('-').reverse().join('-'));
                $('#edt-blood').val(data?.blood).trigger('change');
                $('#edt-fulladdress').val(data?.fulladdress);

                $('#edt-npwp-filesize').html('');
                $('#edt-npwp-status').html('');
                $('#edt-npwp-base64').val('');
                $('#edt-npwp-file').val('');
                $('#edt-npwp-img').attr('src', State.storage_lara + data?.npwp_img);
                $('#edt-npwp-no').val(data?.npwp_string);

                $('#edt-license-filesize').html('');
                $('#edt-license-status').html('');
                $('#edt-license-base64').val('');
                $('#edt-license-file').val('');
                $('#edt-license-img').attr('src', State.storage_lara + data?.license_img);
                $('#edt-license-no').val(data?.license_number);
                $('#edt-license-exp').val(data?.license_exp?.split('-').reverse().join('-'));

                $('#edt-em-fullname').val(data?.em_fullname);
                $('#edt-em-relationship').val(data?.em_relationship).trigger('change');
                $('#edt-em-phone').val(data?.em_phone);

                $('#edt-bank').val(data.bank_code).trigger('change');
                $('#edt-kcp').val(data.bank_branch_name);
                $('#edt-acc_number').val(data.bank_acc_number);
                $('#edt-acc_name').val(data.bank_acc_name);

                $('#edt-vendor_id').val(data?.vendor_id).trigger('change');

                $('#mdlEdtDrv').data('id', data.id);
                $('#mdlEdtDrv').modal('show');
            },
            getData: function() {
                let data = {};
                data.did = $('#mdlEdtDrv').data('id');
                data.ktp_base64 = $('#edt-ktp-base64').val().replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
                data.nik = $('#edt-nik').val();
                data.fullname = $('#edt-fullname').val();
                data.phone = $('#edt-phone').val();
                data.email = $('#edt-email').val();
                data.dob = $('#edt-dob').val().split('-').reverse().join('-');
                data.age = moment().diff(moment(data.dob), 'years', false) || null;
                data.blood = $('#edt-blood').val();
                data.fulladdress = $('#edt-fulladdress').val();

                data.license_base64 = $('#edt-license-base64').val().replace(/^data:image\/(png|jpg|jpeg);base64,/,
                    '');
                data.license_number = $('#edt-license-no').val();
                data.license_exp = $('#edt-license-exp').val().split('-').reverse().join('-');

                data.em_fullname = $('#edt-em-fullname').val();
                data.em_relationship = $('#edt-em-relationship').val();
                data.em_phone = $('#edt-em-phone').val();

                let selectedBank = $('#edt-bank :selected');
                if (selectedBank && selectedBank.val() != '') {
                    data.bank_id = selectedBank.data('id');
                    data.bank_code = selectedBank.data('code');
                    data.bank_short = selectedBank.data('short');
                    data.bank_name = selectedBank.data('name');
                }
                data.bank_branch_name = $('#edt-kcp').val();
                data.bank_acc_number = $('#edt-acc_number').val();
                data.bank_acc_name = $('#edt-acc_name').val();

                data.vendor_id = $('#edt-vendor_id').val();
                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitEdtDrv').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitEdtDrv').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_edit_driver', '') }}/" + data.did,
                        method: 'PUT',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitEdtDrv').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success update driver');
                            $('#mdlEdtDrv').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitEdtDrv').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                });
            },
        }

        const DDel = {
            activate: function() {
                DDel.event();
            },
            event: function() {
                // on table
                $('#tDrivers').on('click', '.btnDelDrv', function(e) {
                    let row = $(e.target).closest('tr');
                    let did = row.find('td[data-did]').data('did');
                    let fullname = row.find('td[data-fullname]').data('fullname');
                    let phone = row.find('td[data-phone]').data('phone');
                    let phone_code = row.find('td[data-phone_code]').data('phone_code');
                    DDel.passDataToView({
                        did,
                        fullname,
                        phone,
                        phone_code,
                    });
                    $('#mdlDelDrv').data('id', did);
                    $('#mdlDelDrv').modal('show');
                });
                $('#btnSubmitDelDrv').on('click', function() {
                    let data = {
                        did: $('#mdlDelDrv').data('id'),
                    };
                    DDel.submitData(data);
                });
                // on modal update
                $('#btnDelDrv_updt').on('click', function(e) {
                    let data = DUpdate.getData();
                    DDel.passDataToView({
                        did: data.did,
                        fullname: data.fullname,
                        phone: data.phone,
                        phone_code: 62,
                    });
                    $('#mdlDelDrv').data('id', data.did);
                    $('#mdlDelDrv').modal('show');
                });
            },
            passDataToView: function(data) {
                data.phone = '' + data.phone
                $('#del-fullname').text(data.fullname);
                $('#del-phone').text(`+${data.phone_code} ${Helper.splitEvery4Char(data.phone)}`);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelDrv').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelDrv').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_del_driver', '') }}/" + data.did,
                        method: 'DELETE',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitDelDrv').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success delete driver');
                            $('#mdlDelDrv').modal('hide');
                            $('#mdlEdtDrv').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelDrv').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                })
            },
        }

        const Filter = {
            activate: function() {
                Filter.event();
            },
            event: function() {},
            triggerFilterCompany: function() {
                DTable.reload();
            },
        }

        const LoginDriver = {
            activate: function() {
                LoginDriver.event();
            },
            event: function() {
                $('#btnResetLogin_updt').on('click', function() {
                    let data = {
                        phone_code: 62,
                    };
                    data.fullname = $('#edt-fullname').val();
                    data.phone = $('#edt-phone').val();
                    data.phone2 = $('#edt-phone2').val();

                    $('#resetLogin-fullname').text(data.fullname);
                    $('#resetLogin-phone').text(`+${data.phone_code} ${Helper.splitEvery4Char(data.phone)}`);
                    $('#mdlWarnResetLoginDriver').modal('show');
                });
                $('#btnResetLogin').on('click', function() {
                    let data = {
                        did: $('#mdlEdtDrv').data('id'),
                    };
                    LoginDriver.resetLogin(data);
                });
            },
            resetLogin: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnResetLogin').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnResetLogin').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_reset_login_driver', '') }}/" + data.did,
                        method: 'DELETE',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnResetLogin').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success reset login driver');
                            $('#mdlWarnResetLoginDriver').modal('hide');
                            $('#mdlEdtDrv').modal('hide');
                            // DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnResetLogin').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                });
            },
        }

        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)
                }
            });
        }
        // Compress image: ktp, license, npwp
        const JimpWorkerAdd = {
            worker_ktp: null,
            worker_npwp: null,
            worker_license: null,
            activate: function(x) {
                let linkWorker = State.file_jimp_worker
                this.setWorker(linkWorker, x, function(res) {
                    if (res.stts) {
                        let pureDataURL = res.data.replace(/^data:image\/(png|jpg|jpeg);base64,/, '')
                        let fileSize = window.atob(pureDataURL).length // in Byte
                        // (fileSize/1000) + ' Kb'
                        $('#add-group_' + x + '_spinner').addClass('d-none');
                        // $('#add-' + x + '-status').html('Compressed')
                        // $('#add-' + x + '-filesize').html('<samp>(' + fileSize / 1000 + ' Kb)</samp>')
                        $('#add-' + x + '-img').attr('src', res.data)
                        $('#add-' + x + '-img').removeClass('d-none')
                        $('#add-' + x + '-base64').val(res.data)
                    } else {
                        console.error(res.data)
                    }
                    $('.page-loader-wrapper').fadeOut()
                });
            },
            runWorker: function(dataURL, x) {
                $('#add-group_' + x + '_spinner').removeClass('d-none');
                $('#add-' + x + '-img').addClass('d-none');
                if (x == 'ktp') {
                    this.worker_ktp.postMessage(dataURL)
                } else if (x == 'npwp') {
                    this.worker_npwp.postMessage(dataURL)
                } else if (x == 'license') {
                    this.worker_license.postMessage(dataURL)
                }
            },
            setWorker: function(urlFileJs, x, cbFinish) {
                let worker = new Worker(urlFileJs);
                worker.onmessage = function(e) {
                    // e = {status:(true,false), data:(dataURL)}

                    // append a new img element using the base 64 image
                    // let img = document.createElement('img');
                    // img.setAttribute('src', e.data);
                    // document.body.appendChild(img);

                    cbFinish(e.data);
                };
                if (x == 'ktp') {
                    this.worker_ktp = worker
                } else if (x == 'npwp') {
                    this.worker_npwp = worker
                } else if (x == 'license') {
                    this.worker_license = worker
                }
            }
        }
        const DUploadAdd = {
            activate: function(x) {
                this.initReader(x)
                JimpWorkerAdd.activate(x)
                this.event(x)
                DRotateImgAdd.activate(x)
            },
            event: function(x) {
                $('#add-' + x + '-choose').on('click', function(e) {
                    $('#add-' + x + '-file').trigger('click')
                })
            },
            initReader: function(x) {
                let reader = new FileReader();
                reader = this.setEventFile(reader, x);
                $('#add-' + x + '-file').on('change', async function(e) {
                    try {
                        if (browserBack()) return false;
                        let file = e.target.files[0];
                        let type = file.type.split('/');
                        if (type[1] == 'jpeg' || type[1] == 'png' || type[1] == 'jpg') {
                            $('.page-loader-wrapper').fadeIn()

                            // fix auto rotate when select file
                            let newImg = await loadImage(file, {
                                orientation: true
                            })

                            let newFile = await convertImgHtmlToFile(newImg.image, newImg
                                .originalWidth, newImg.originalHeight, file.type, file
                                .name)

                            DUploadAdd.readFile(reader, newFile);

                            $('#add-' + x + '-filesize').html('')
                            // $('#add-' + x + '-status').html('Loading on compressing...')
                            // $('#add-' + x + '-img').attr('src', '')
                            $('#add-' + x + '-base64').val('')
                        } else {
                            Helper.toast('Validasi', 'just-now', 'Gambar tidak valid');
                        }
                    } catch (e) {
                        console.error(e.message)
                    }
                })
            },
            setEventFile: function(reader, x) {
                reader.onload = function(e) {
                    let data = e.target.result;
                    $('#add-' + x + '-img-old').attr('src',
                        data) // preview, -old mungkin kedepannya bakal diganti jadi -new
                    // $('#add-'+x+'-img-base64').val(data) // real-data
                    console.log('Compressing ' + x);
                    JimpWorkerAdd.runWorker(data, x)
                    DRotateImgAdd.toggleBtnRotate(x, 'show');
                };

                reader.onerror = function(err) {
                    $('.page-loader-wrapper').fadeOut()
                    $('#' + x).attr('hidden', true)
                    console.error(err);
                };

                reader.onabort = function(err) {
                    console.log(err);
                }

                return reader;
            },
            readFile: function(reader, file) {
                // reader.readAsArrayBuffer(file);
                reader.readAsDataURL(file);
            },
        }
        const DRotateImgAdd = {
            activate: function(id) {
                this.event(id)
            },
            event: function(id) {
                $('#add-group_rotate_' + id).on('click', '.btnRotateRight', function(e) {
                    DRotateImgAdd.rotateBase64Image($('#add-' + id + '-base64').val(), 90).then(
                        function(base64) {
                            DRotateImgAdd.updateImg(id, base64)
                        })
                })
                $('#add-group_rotate_' + id).on('click', '.btnRotateLeft', function(e) {
                    DRotateImgAdd.rotateBase64Image($('#add-' + id + '-base64').val(), -90).then(
                        function(base64) {
                            DRotateImgAdd.updateImg(id, base64)
                        })
                })
            },
            rotateBase64Image: function(base64data, degrees) {
                return new Promise((resolve, reject) => {
                    try {
                        let x = 0,
                            y = 0,
                            w = 0,
                            h = 0;
                        let canvas = document.createElement("canvas");
                        let image = document.createElement("img"); // new Image();
                        image.src = base64data; // image.src = 'data:image/jpg;base64,' + base64data;
                        image.onload = function() {
                            // current image size for processing rotate
                            w = image.width;
                            h = image.height;
                            let angle = degrees * Math.PI / 180.0; // angle/rads
                            let ctx = canvas.getContext("2d");

                            // new image size for after cropped
                            let c = Math.cos(angle);
                            let s = Math.sin(angle);
                            if (s < 0) {
                                s = -s;
                            }
                            if (c < 0) {
                                c = -c;
                            }
                            let rw = h * s + w * c;
                            let rh = h * c + w * s;

                            // set canvas size
                            canvas.width = rw;
                            canvas.height = rh;
                            // save the unrotated context of the canvas so we can restore it later
                            // the alternative is to untranslate & unrotate after drawing
                            ctx.save();
                            // draw the rect in the center of the newly sized canvas
                            ctx.clearRect(0, 0, canvas.width, canvas.height);
                            // move to the center of the canvas
                            // ctx.translate(x+w/2, y+h/2); // ctx.translate(x, h);
                            // move to the upper left corner when rotating in 90deg increments
                            ctx.translate(Math.abs(w / 2 * Math.cos(angle) + h / 2 * Math.sin(angle)),
                                Math.abs(h / 2 * Math.cos(angle) + w / 2 * Math.sin(angle)));
                            // rotate the canvas to the specified degrees
                            ctx.rotate(angle); // ctx.rotate(180 * Math.PI / 180);
                            // move to the center of the canvas (origin)
                            ctx.translate(-x - w / 2, -y - h / 2);
                            // since the context is rotated, the image will be rotated also
                            ctx.drawImage(image, 0, 0, w, h);
                            // we’re done with the rotating so restore the unrotated context
                            ctx.restore();
                            // convert to base64
                            resolve(canvas.toDataURL('image/jpeg', 1.0));
                        };
                    } catch (err) {
                        reject(err);
                    }
                });
            },
            updateImg: function(id, base64) {
                // update data
                let pureDataURL = base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, '')
                let fileSize = window.atob(pureDataURL).length // in Byte
                // (fileSize/1000) + ' Kb'
                $('#add-' + id + '-status').html('Compressing...')
                $('#add-' + id + '-filesize').html('<samp>(' + fileSize / 1000 + ' Kb)</samp>')
                $('#add-' + id + '-img').attr('src', base64)
                $('#add-' + id + '-base64').val(base64) // real-data

                // compress again because base64 from rotate is rather bigger in range 200kb than compress 50kb
                JimpWorkerAdd.runWorker(base64, id)
                // if (id == 'ktp') {
                //     JimpWorkerAdd.worker_ktp.postMessage(base64)
                // } else if (id == 'npwp') {
                //     JimpWorkerAdd.worker_npwp.postMessage(base64)
                // } else if (id == 'license') {
                //     JimpWorkerAdd.worker_license.postMessage(base64)
                // }
            },
            toggleBtnRotate: function(id, hide = 'hidden') {
                if (hide == 'show') {
                    $('#add-group_rotate_' + id).removeClass('d-none')
                    return true;
                }
                $('#add-group_rotate_' + id).addClass('d-none')
                return true;
            },
        }

        const JimpWorkerEdt = {
            worker_ktp: null,
            worker_npwp: null,
            worker_license: null,
            activate: function(x) {
                let linkWorker = State.file_jimp_worker
                this.setWorker(linkWorker, x, function(res) {
                    if (res.stts) {
                        let pureDataURL = res.data.replace(/^data:image\/(png|jpg|jpeg);base64,/, '')
                        let fileSize = window.atob(pureDataURL).length // in Byte
                        // (fileSize/1000) + ' Kb'
                        $('#edt-group_' + x + '_spinner').addClass('d-none');
                        // $('#edt-' + x + '-status').html('Compressed')
                        // $('#edt-' + x + '-filesize').html('<samp>(' + fileSize / 1000 + ' Kb)</samp>')
                        $('#edt-' + x + '-img').attr('src', res.data)
                        $('#edt-' + x + '-img').removeClass('d-none');
                        $('#edt-' + x + '-base64').val(res.data)
                    } else {
                        console.error(res.data)
                    }
                    $('.page-loader-wrapper').fadeOut()
                });
            },
            runWorker: function(dataURL, x) {
                $('#edt-group_' + x + '_spinner').removeClass('d-none');
                $('#edt-' + x + '-img').addClass('d-none');
                if (x == 'ktp') {
                    this.worker_ktp.postMessage(dataURL)
                } else if (x == 'npwp') {
                    this.worker_npwp.postMessage(dataURL)
                } else if (x == 'license') {
                    this.worker_license.postMessage(dataURL)
                }
            },
            setWorker: function(urlFileJs, x, cbFinish) {
                let worker = new Worker(urlFileJs);
                worker.onmessage = function(e) {
                    // e = {status:(true,false), data:(dataURL)}

                    // append a new img element using the base 64 image
                    // let img = document.createElement('img');
                    // img.setAttribute('src', e.data);
                    // document.body.appendChild(img);

                    cbFinish(e.data);
                };
                if (x == 'ktp') {
                    this.worker_ktp = worker
                } else if (x == 'npwp') {
                    this.worker_npwp = worker
                } else if (x == 'license') {
                    this.worker_license = worker
                }
            }
        }
        const DUploadEdt = {
            activate: function(x) {
                this.initReader(x)
                JimpWorkerEdt.activate(x)
                this.event(x)
                DRotateImgEdt.activate(x)
            },
            event: function(x) {
                $('#edt-' + x + '-choose').on('click', function(e) {
                    $('#edt-' + x + '-file').trigger('click')
                })
            },
            initReader: function(x) {
                let reader = new FileReader();
                reader = this.setEventFile(reader, x);
                $('#edt-' + x + '-file').on('change', async function(e) {
                    try {
                        if (browserBack()) return false;
                        let file = e.target.files[0];
                        let type = file.type.split('/');
                        if (type[1] == 'jpeg' || type[1] == 'png' || type[1] == 'jpg') {
                            $('.page-loader-wrapper').fadeIn()

                            // fix auto rotate when select file
                            let newImg = await loadImage(file, {
                                orientation: true
                            })

                            let newFile = await convertImgHtmlToFile(newImg.image, newImg
                                .originalWidth, newImg.originalHeight, file.type, file
                                .name)

                            DUploadEdt.readFile(reader, newFile);

                            $('#edt-' + x + '-filesize').html('')
                            // $('#edt-' + x + '-status').html('Loading on compressing...')
                            // $('#edt-' + x + '-img').attr('src', '')
                            $('#edt-' + x + '-base64').val('')
                        } else {
                            Helper.toast('Validasi', 'just-now', 'Gambar tidak valid');
                        }
                    } catch (e) {
                        console.error(e.message)
                    }
                })
            },
            setEventFile: function(reader, x) {
                reader.onload = function(e) {
                    let data = e.target.result;
                    $('#edt-' + x + '-img-old').attr('src',
                        data) // preview, -old mungkin kedepannya bakal diganti jadi -new
                    // $('#edt-'+x+'-img-base64').val(data) // real-data
                    console.log('Compressing ' + x);
                    JimpWorkerEdt.runWorker(data, x)
                    DRotateImgEdt.toggleBtnRotate(x, 'show');
                };

                reader.onerror = function(err) {
                    $('.page-loader-wrapper').fadeOut()
                    $('#' + x).attr('hidden', true)
                    console.error(err);
                };

                reader.onabort = function(err) {
                    console.log(err);
                }

                return reader;
            },
            readFile: function(reader, file) {
                // reader.readAsArrayBuffer(file);
                reader.readAsDataURL(file);
            },
        }
        const DRotateImgEdt = {
            activate: function(id) {
                this.event(id)
            },
            event: function(id) {
                $('#edt-group_rotate_' + id).on('click', '.btnRotateRight', function(e) {
                    DRotateImgEdt.rotateBase64Image($('#edt-' + id + '-base64').val(), 90).then(
                        function(base64) {
                            DRotateImgEdt.updateImg(id, base64)
                        })
                })
                $('#edt-group_rotate_' + id).on('click', '.btnRotateLeft', function(e) {
                    DRotateImgEdt.rotateBase64Image($('#edt-' + id + '-base64').val(), -90).then(
                        function(base64) {
                            DRotateImgEdt.updateImg(id, base64)
                        })
                })
            },
            rotateBase64Image: function(base64data, degrees) {
                return new Promise((resolve, reject) => {
                    try {
                        let x = 0,
                            y = 0,
                            w = 0,
                            h = 0;
                        let canvas = document.createElement("canvas");
                        let image = document.createElement("img"); // new Image();
                        image.src = base64data; // image.src = 'data:image/jpg;base64,' + base64data;
                        image.onload = function() {
                            // current image size for processing rotate
                            w = image.width;
                            h = image.height;
                            let angle = degrees * Math.PI / 180.0; // angle/rads
                            let ctx = canvas.getContext("2d");

                            // new image size for after cropped
                            let c = Math.cos(angle);
                            let s = Math.sin(angle);
                            if (s < 0) {
                                s = -s;
                            }
                            if (c < 0) {
                                c = -c;
                            }
                            let rw = h * s + w * c;
                            let rh = h * c + w * s;

                            // set canvas size
                            canvas.width = rw;
                            canvas.height = rh;
                            // save the unrotated context of the canvas so we can restore it later
                            // the alternative is to untranslate & unrotate after drawing
                            ctx.save();
                            // draw the rect in the center of the newly sized canvas
                            ctx.clearRect(0, 0, canvas.width, canvas.height);
                            // move to the center of the canvas
                            // ctx.translate(x+w/2, y+h/2); // ctx.translate(x, h);
                            // move to the upper left corner when rotating in 90deg increments
                            ctx.translate(Math.abs(w / 2 * Math.cos(angle) + h / 2 * Math.sin(angle)),
                                Math.abs(h / 2 * Math.cos(angle) + w / 2 * Math.sin(angle)));
                            // rotate the canvas to the specified degrees
                            ctx.rotate(angle); // ctx.rotate(180 * Math.PI / 180);
                            // move to the center of the canvas (origin)
                            ctx.translate(-x - w / 2, -y - h / 2);
                            // since the context is rotated, the image will be rotated also
                            ctx.drawImage(image, 0, 0, w, h);
                            // we’re done with the rotating so restore the unrotated context
                            ctx.restore();
                            // convert to base64
                            resolve(canvas.toDataURL('image/jpeg', 1.0));
                        };
                    } catch (err) {
                        reject(err);
                    }
                });
            },
            updateImg: function(id, base64) {
                // update data
                let pureDataURL = base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, '')
                let fileSize = window.atob(pureDataURL).length // in Byte
                // (fileSize/1000) + ' Kb'
                $('#edt-' + id + '-status').html('Compressing...')
                $('#edt-' + id + '-filesize').html('<samp>(' + fileSize / 1000 + ' Kb)</samp>')
                $('#edt-' + id + '-img').attr('src', base64)
                $('#edt-' + id + '-base64').val(base64) // real-data

                // compress again because base64 from rotate is rather bigger in range 200kb than compress 50kb
                JimpWorkerEdt.runWorker(base64, id)
                // if (id == 'ktp') {
                //     JimpWorkerEdt.worker_ktp.postMessage(base64)
                // } else if (id == 'npwp') {
                //     JimpWorkerEdt.worker_npwp.postMessage(base64)
                // } else if (id == 'license') {
                //     JimpWorkerEdt.worker_license.postMessage(base64)
                // }
            },
            toggleBtnRotate: function(id, hide = 'hidden') {
                if (hide == 'show') {
                    $('#edt-group_rotate_' + id).removeClass('d-none')
                    return true;
                }
                $('#edt-group_rotate_' + id).addClass('d-none')
                return true;
            },
        }

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