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

@extends('app.app')

@section('title')
    Zone
@endsection

@section('customcss')
    <style>
        .no-hover:hover {
            cursor: default;
            background-color: inherit;
            color: initial;
        }
    </style>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="row">
                <div class="col-sm-12">
                    <div class="card">
                        <div class="card-header">
                            <div class="row d-flex align-items-center">
                                <div class="col">
                                    {{-- <p class="card-title text-bold mb-0">Zona (<span id="count_zones"></span>)</p> --}}
                                    <p class="card-title text-bold mb-0">Zona</p>
                                </div>
                                @if ($user_role === \App\Models\Users::ROLE_ADMIN || \App\Models\Users::ROLE_VENDOR)
                                    {{-- @if ($user_role === \App\Models\Users::ROLE_VENDOR) --}}
                                    @can('zone.create')
                                        <div class="col text-end">
                                            {{-- <a href="#" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#addNewZoneModal">Add New Zone</a> --}}
                                            <a href="{{ route('view_zone_add') }}" class="btn btn-sm btn-danger">Add New Zone</a>
                                        </div>
                                    @endcan
                                @endif
                                <div class="col-auto text-end ps-0">
                                    {{-- <button class="btn btn-sm btn-danger">Upload</button> --}}
                                    {{-- <button class="btn btn-sm btn-danger">Download</button> --}}
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="tZones" class="table table-hover dataTable w-100">
                                    <thead>
                                        <tr class="">
                                            <th class="">#</th>
                                            <th class="text-center">Action</th>
                                            <th class="text-nowrap">Zone</th>
                                            <th class="text-nowrap">Company</th>
                                            <th class="text-nowrap">Zone Type</th>
                                            <th class="text-nowrap">Workflow</th>
                                            <th class="text-nowrap">Address</th>
                                            <th class="text-nowrap">Postal Code</th>
                                            <th class="text-nowrap">Zone Shape</th>
                                            <th class="text-nowrap">Created At</th>
                                            <th class="text-nowrap">Last Updated</th>
                                            <th class="text-center">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr class="">
                                            <td class="">1</td>
                                            <td class="">
                                                XXIOAS-001<br>
                                                <a href="#" class="text-danger"><small>Preview</small></a>
                                            </td>
                                            <td class="">JNE</td>
                                            <td class="text-nowrap">Warehouse</td>
                                            <td class="text-nowrap">Pickup</td>
                                            <td class="text-nowrap">Jl. Letjen Mt. Haryono No.Kav. 20, RW.1, Cawang, Kec.
                                                Kramat jati, Kota Jakarta Timur, Daerah Khusus Ibukota Jakarta 13630</td>
                                            <td class="text-nowrap">13630</td>
                                            <td class="text-start">Poligon</td>
                                            <td class="text-nowrap">
                                                Jan 13, 2022 08:58:07 <br>
                                                <small class="text-muted">JNE</small>
                                            </td>
                                            <td class="text-nowrap">
                                                Jan 19, 2022 20:42:57 <br>
                                                <small class="text-muted">Administrator</small>
                                            </td>
                                            <th class="text-center">
                                                <span class="btn btn-sm btn-outline-success">Active</span>
                                            </th>
                                            <td class="align-baseline text-center text-nowrap">
                                                <a href="#" class="text-decoration-none me-1" data-bs-toggle="tooltip" data-bs-placement="bottom" title="View">
                                                    <span class="icon ion-eye text-inherit fz-16"></span>
                                                </a>
                                                <a href="#" class="text-decoration-none me-1" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                                                    <span class="icon ion-edit text-inherit fz-16"></span>
                                                </a>
                                                <a href="#" class="text-decoration-none text-danger" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete">
                                                    <span class="icon ion-trash-b fz-16"></span>
                                                </a>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-8"></div>
            </div>
        </div>
    </div>

    {{-- MODAL --}}
    @if ($user_role === \App\Models\Users::ROLE_ADMIN)
        <div class="modal fade" id="addNewZoneModal" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="addNewZoneModal" aria-hidden="true">
            <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-md">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addNewZoneModal">Add New Zone</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body pb-0">
                        <div class="row">
                            <div class="col-sm-12">
                                <h6>Zone Infomation</h6>
                                <div class="mb-3">
                                    <label for="" class="form-label">Name</label>
                                    <input type="text" class="form-control form-control-sm" name="" id="">
                                </div>
                                <div class="mb-3">
                                    <label for="" class="form-label">Type</label>
                                    <select name="" id="" class="form-control select2">
                                        <option value="">Warehouse</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="" class="form-label">Workflow Zone Type</label>
                                    <select name="" id="" class="form-control select2">
                                        <option value="">Origin</option>
                                        <option value="">Destination</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="" class="form-label">Ship-To Code</label>
                                    <input type="number" class="form-control form-control-sm" name="" id="">
                                </div>
                                <div class="mb-3">
                                    <label for="" class="form-label">Address</label>
                                    <textarea name="" id="" class="form-control form-control-sm" rows="3"></textarea>
                                </div>
                                <div class="mb-4">
                                    <button class="btn btn-sm btn-outline-danger d-block">Draw Boundary</button>
                                </div>
                            </div>
                            <div class="col-sm-12">
                                <div class="row">
                                    <div class="col-12">
                                        <h6>Utilities</h6>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="mb-3">
                                            <label for="" class="form-label">Zone Status</label>
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault" checked>
                                                <label class="form-check-label" for="flexSwitchCheckDefault"><span class="text-dark" id="txtStatus">Active</span></label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-sm btn-danger">Submit data</button>
                    </div>
                </div>
            </div>
        </div>
    @endif

    <div class="modal fade" id="delZoneModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="delZoneModal" 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="delZoneModal">Delete Zone</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 zone
                            <a href="#" class="text-danger">
                                <span id="del-name"></span>
                                (<span id="del-client_group_name"></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="btnSubmitDelZone" type="button" class="btn btn-sm btn-secondary">Yes, delete</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('customjs')
    <script>
        // $('.dataTable').DataTable();
        $('.select2').select2({
            width: '100%',
            dropdownParent: $("#addNewZoneModal")
        })
        $('#flexSwitchCheckDefault').bind('change', function() {
            if ($(this).is(':checked'))
                $('#txtStatus').html('Active')
            else
                $('#txtStatus').html('Inactive')
        });
    </script>
    <script>
        'use strict';
        const State = {
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            storage_lara: "{{ asset('storage') }}/",
            zone_status: {
                active: "{{ App\Models\Zone::STATUS_ACTIVE }}",
                inactive: "{{ App\Models\Zone::STATUS_INACTIVE }}",
            },
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                ZDel.activate();
                Filter.activate();
            },
            event: function() {
                $('#tZones').on('click', '.btnEdtZone', function(e) {
                    let zid = $(e.target).closest('tr').find('td[data-id]').data('id');
                    window.location.href = "{{ route('view_zone_edit', '') }}/" + zid;
                })
            },
        };

        const DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tZones').DataTable();
                // if (Zone.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Zone.Table.firstInitDataTable = 1; }
                $('#tZones').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_list_zones') }}?cptid=" + AppState.current_company,
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_zones').text(count);
                            }
                            // 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) {
                                // <a href="#" class="text-decoration-none me-1 btnViewZone" data-bs-toggle="tooltip"
                                // 	data-bs-placement="bottom" title="View">
                                // 	<span class="icon ion-eye fz-16"></span>
                                // </a>
                                let action = `
                                    <a href="#" class="text-decoration-none me-1 btnEdtZone" data-bs-toggle="tooltip"
                                        data-bs-placement="bottom" title="Edit">
                                        <span class="icon ion-edit fz-16"></span>
                                    </a>
								`;
                                // <a href="#" class="text-decoration-none text-danger btnDelZone"
                                //     data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete">
                                //     <span class="icon ion-trash-b fz-16"></span>
                                // </a>
                                return action;
                            }
                        },
                        {
                            data: 'name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-id', rowData.id);
                                $(td).attr('data-name', rowData.name);
                                $(td).attr('data-client_group_name', rowData.client_group_name);
                            },
                            render: function(data, type, row, meta) {
                                return `
                                ${data}<br>
                                `;
                            }
                        },
                        {
                            data: 'client_group_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return data || '-';
                            },
                        },
                        {
                            data: 'type_name',
                            className: 'text-start text-nowrap text-capitalize',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'workflow_type_name',
                            className: 'text-start text-nowrap text-capitalize',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'fulladdress',
                            className: 'text-start',
                            width: 200,
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'shiptocode',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'boundary_type',
                            className: 'text-start text-nowrap text-capitalize',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'crt',
                            className: 'text-center text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                // <small class="text-muted">${row.crt_client_group_name}</small>
                                return `
                                    ${moment.unix(data).format('DD MMM YYYY HH:mm')}<br>
                                    <small class="text-muted">${row.crt_name}</small>
                                `;
                            },
                        },
                        {
                            data: 'updt',
                            className: 'text-center text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                // <small class="text-muted">${row.updt_role_name}</small>
                                return `
                                    ${moment.unix(data).format('DD MMM YYYY HH:mm')}<br>
                                    <small class="text-muted">${row.updt_name}</small>
                                `;
                            },
                        },
                        {
                            data: 'status',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data == State.zone_status.active) {
                                    return '<span class="badge rounded-pill bg-success">Active</span>';
                                }
                                return '<span class="badge rounded-pill bg-danger">Inactive</span>';
                            },
                        },
                    ],
                });
            },
        };

        const ZDel = {
            activate: function() {
                ZDel.event();
            },
            event: function() {
                // modal
                $('#tZones').on('click', '.btnDelZone', function(e) {
                    let row = $(e.target).closest('tr');
                    let zid = row.find('td[data-id]').data('id');
                    let name = row.find('td[data-name]').data('name');
                    let client_group_name = row.find('td[data-client_group_name]').data(
                        'client_group_name');
                    ZDel.passDataToView({
                        zid,
                        name,
                        client_group_name,
                    });
                    $('#delZoneModal').data('id', zid);
                    $('#delZoneModal').modal('show');
                });
                $('#btnSubmitDelZone').on('click', function() {
                    let data = {
                        zid: $('#delZoneModal').data('id'),
                    };
                    ZDel.submitData(data);
                });
            },
            passDataToView: function(data) {
                $('#del-name').text(data.name);
                $('#del-client_group_name').text(data.client_group_name);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelZone').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelZone').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_del_zone', '') }}/" + data.zid,
                        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) => {
                            $('#btnSubmitDelZone').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 zone');
                            $('#delZoneModal').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelZone').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();
            },
        }

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