@extends('app.app')

@section('title')
    Conf Pools
@endsection

@section('customcss')
    <style>

    </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">Pool / Area</p>
                        </div>
                        @can('config_pool.create')
                            <div class="col text-end">
                                <button id="btnMdlNew" class="btn btn-sm btn-danger">Add New Pool</button>
                            </div>
                        @endcan

                        <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="tList" class="table table-hover dataTable w-100">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center">Action</th>
                                    <th class="">Code</th>
                                    <th class="">Name</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlNew" aria-labelledby="mdlLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlLabel">Add New Pool</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="fNew">		
						<!--input hidden  -->
						<input type="hidden" name="tipe" id="tipe" value="new">
						<input type="hidden" name="id" id="id">
                        <div class="mb-3">
                            <div class="row">
                                <div class="col-12">
                                    <label for="pool_code" class="col-form-label">Code:</label>
                                    <input type="text" name="pool_code" id="pool_code" class="form-control" placeholder="Pool code, example: VF, VO, etc">
                                </div>
                                <div class="col-12">
                                    <label for="pool_name" class="col-form-label">Name:</label>
                                    <input type="text" name="pool_name" id="pool_name" class="form-control" placeholder="Pool name">
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    @can('config_pool.delete')
                        <button type="button" id="btnDel" class="btn btn-sm btn-warning">Delete ?</button>
                    @endcan
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmit" type="button" class="btn btn-sm btn-danger">Submit data</button>
                    @can('config_pool.edit')
                        <button id="btnEdit" type="button" class="btn btn-sm btn-danger">Update data</button>
                    @endcan
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlDel" aria-labelledby="mdlDelLabel" 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="mdlDelLabel">Delete TruckType</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 Pool
                            <a href="#" class="text-danger">
                                <span id="del-type_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="btnSubmitDel" 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') }}/",
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
			},
            event: function() {
                $('#btnMdlNew').on('click', function() {
					$('#fNew')[0].reset();
					$('#btnDel').hide();
					$('#btnEdit').hide();
					$('#btnSubmit').show();
					$('#mdlLabel').text('New Pool');
					$('#pool_code').focus();
					
                    $('#mdlNew').modal('show');
                });

				$('#btnSubmit, #btnEdit').on('click', function() {
					let data=$("#fNew").serialize()
					Wrapper.submitData(data);
				});

				$('#tList').on('click', '.btnUpdt', function(e) {
					// console.log("updt klik");
					const id = $(this).data('id');
                    $.ajax({
                        url: "{{ route('api_conf_show_pool', '') }}/" + id,
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        // data: params,
                        success: (data, textStatus, jqXHR) => {
							console.log("res data", data);
							
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }

							//  insert value
							$('#mdlLabel').text('Edit Pool');
							$('#btnDel').show();
							$('#btnEdit').show();
							$('#btnSubmit').hide();

							$('#tipe').val("edit");
							$('#id').val(id);
							$('#pool_code').val(data.data.pool_code);
							$('#pool_name').val(data.data.pool_name);
                        },
                        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'
                            });
                        }
                    })

					$('#mdlNew').modal('show');
				});

                $('#btnDel').on('click', function(e) {
                    $('#mdlDel').modal('show');
                });

				$('#btnSubmitDel').on('click', function(e) {
					const id = $('#id').val()
					const data = {
						id: $('#mdlDel').data('id'),
					};
                    $('#btnSubmitDel').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_conf_del_pool', '') }}/" + id,
                        method: 'DELETE',
                        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) => {
                            $('#btnSubmitDel').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 Pool');
                            $('#mdlDel').modal('hide');
                            $('#mdlNew').modal('hide');
                            $('#tList').DataTable().ajax.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDel').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'
                            });
                        }
                    })
                })

				$('#mdlDel').on('show.bs.modal', function () {
					$('#mdlNew').css('opacity', '0.5'); // fade background modal
				});

				$('#mdlDel').on('hidden.bs.modal', function () {
					$('#mdlNew').css('opacity', '1');
				});
			},
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmit').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmit').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_conf_add_pool') }}",
                        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) => {
                            $('#btnSubmit').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 Pool');
                            $('#mdlNew').modal('hide');
                            $('#tList').DataTable().ajax.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmit').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 DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tList').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                $('#tList').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_conf_list_pool') }}",
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_trucktypes').text(count);
                            }
                            // removeTableSkeletonLoading()
                        },
                    },
                    deferRender: true,
                    columns: [{
                            data: 'DT_RowIndex',
                            className: 'text-end',
                            visible: true,
                            orderable: true,
                            searchable: true,
							width: "30px"
                        },
                        {
                            data: 'action',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
							width: "100px",
                            render: function(data, type, row, meta) {
                                let action = `
									<a href="#" class="text-decoration-none me-1 btnUpdt" data-id="${row.id}" title="Update" data-bs-toggle="tooltip" data-bs-placement="top">
										<span class="icon ion-eye fz-16"></span>
									</a>
								`;
                                return action;
                            }
                        },
                        {
                            data: 'pool_code',
                            className: 'text-left text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-ttid', rowData.id);
                                $(td).attr('data-type_name', rowData.type_name);
                            },
                        },
                        {
                            data: 'pool_name',
                            className: 'text-left',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                    ],
                });
            },
        };


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