@extends('admin.layout.page-app')
@section('page_title', __('label.sub_in_charge'))
@section('tab_title', __('label.sub_in_charge'))

@section('content')
    @include('admin.layout.sidebar')

    <!-- Select2 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" />

    <div class="right-content">
        @include('admin.layout.header')

        <div class="body-content">
            <!-- mobile title -->
            <h1 class="page-title-sm">{{__('label.sub_in_charge')}}</h1>

            <div class="border-bottom row">
                <div class="col-sm-10">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">{{__('label.dashboard')}}</a></li>
                        <li class="breadcrumb-item active" aria-current="page">{{__('label.sub_in_charge')}}</li>
                    </ol>
                </div>
                <div class="col-sm-2 d-flex align-items-center justify-content-end">
                    <a href="{{ route('sub_incharge.create') }}" class="btn btn-default mw-130" style="margin-top: -14px;">{{__('label.add_sub_in_charge')}}</a>
                </div>
            </div>

            <!-- Export Files -->
            <div class="page-search mb-3 mt-3">
                <div class="col-8">
                    <label class="text-gray pt-2 font-weight-bold"><i class="fa-solid fa-circle-info fa-2xl mr-3"></i>{{__('label.only_the_following_data_will_be_captured_in_this_file')}}</label>
                </div>
                <div class="col-4">
                    <div class="d-flex justify-content-around">
                        <button id="ms_excel" class="btn btn-default"><i class="fa-sharp fa-solid fa-file-excel mr-2 font-weight-bold"></i>{{__('label.ms_excel')}}</button>
                        <button id="csv" class="btn btn-default"><i class="fa-solid fa-file-csv mr-2 font-weight-bold" style="font-size:18px"></i>{{__('label.csv')}}</button>
                        <button id="pdf" class="btn btn-default"><i class="fa-solid fa-file-pdf mr-2 font-weight-bold" style="font-size:18px"></i>{{__('label.pdf')}}</button>
                    </div>
                </div>
            </div>

            <!-- Search -->
            <div class="page-search mb-3">
                <div class="input-group" title="Search">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="basic-addon1"><i class="fa-solid fa-magnifying-glass fa-xl light-gray"></i></span>
                    </div>
                    <input type="text" id="input_search" class="form-control" placeholder="{{__('label.search_sub_in_charge')}}" aria-label="Search" aria-describedby="basic-addon1">
                </div>
                <div class="sorting mr-4 w-75">
                    <label>{{__('label.sort_by')}}</label>
                    <select class="form-control" name="input_department" id="input_department">
                        <option value="all"> {{__('label.all_department')}} </option>
                        @foreach ($department as $key => $value)
                            <option value="{{$value->id}}">
                                {{ $value->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="sorting w-50">
                    <label>{{__('label.sort_by')}}</label>
                    <select class="form-control" id="input_status">
                        <option value="all">{{__('label.all_status')}}</option>
                        <option value="0">{{__('label.inactive')}}</option>
                        <option value="1">{{__('label.active')}}</option>
                    </select>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-striped text-center table-bordered" id="datatable">
                    <thead>
                        <tr style="background: #F9FAFF;">
                            <th>{{__('label.#')}}</th>
                            <th>{{__('label.image')}}</th>
                            <th>{{__('label.department')}}</th>
                            <th>{{__('label.in_charge')}}</th>
                            <th>{{__('label.full_name')}}</th>
                            <th>{{__('label.transfer')}}</th>
                            <th>{{__('label.status')}}</th>
                            <th>{{__('label.action')}}</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

            <!-- Transfer Model-->
            <div class="modal fade" id="edit_incharge_model" tabindex="-1" data-backdrop="static" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="ModalLabel">{{__('label.transfer_sub_in_charge')}}</h5>
                            <button type="button" class="close text-dark" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <form id="in_charge_update" autocomplete="off">
                            <div class="modal-body">
                                <div class="form-row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label>{{__('label.department')}}</label>
                                            <select class="form-control" name="department_id" id="edit_department_id" style="width: 100%">
                                                <option value="0">{{__('label.select_department')}}</option>
                                                @foreach ($department as $key => $value)
                                                <option value="{{ $value->id}}">
                                                    {{ $value->name }}
                                                </option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-12">
                                        <div class="form-group">
                                            <label>{{__('label.service')}}<span class="text-danger">*</span></label>
                                            <select class="form-control" name="service_id[]" multiple id="service_id" style="width: 100% !important;">
                                                <option value="">{{__('label.select_service')}}</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <input type="hidden" name="id" id="edit_incharge_id">
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default mw-120" onclick="in_charge_update()">{{__('label.update')}}</button>
                                <button type="button" class="btn btn-cancel mw-120" data-dismiss="modal">{{__('label.close')}}</button>
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('pagescript')
    <!-- Export Files LInk (PDF, CSV, MS-Excel) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
    <!-- Select2 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

    <script>
        // Sidebar Scroll Down
		sidebar_down('600px');
        $("#input_department").select2();
        $("#service_id").select2({
			placeholder: "{{__('label.select_service')}}",
		});
        $('#edit_department_id').select2({
            dropdownParent: $('#edit_incharge_model') 
        });

        $(document).ready(function() {
            var table = $('#datatable').DataTable({
                ...dataTableDefaults,
                ajax: {
                    url: "{{ route('sub_incharge.index') }}",
                    data: function(d) {
                        d.input_status = $('#input_status').val();
                        d.input_department = $('#input_department').val();
                        d.input_search = $('#input_search').val();
                    },
                },
                columns: [
                    { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
                    {
						data: 'image',
						name: 'image',
						orderable: false,
						searchable: false,
						render: function(data) {
                            return `<a href='${data}' target='_blank'>
                                        <img src='${data}' class='rounded-circle' style='height:55px; width:55px'>
                                    </a>`;
						},
					},
                    {
                        data: 'department',
                        name: 'department',
                        render: function(data) {
                            return data ? data.name : "-";
                        }
                    },
                    {
                        data: 'in_charge',
                        name: 'in_charge',
                    },
                    {
						data: 'full_name',
						name: 'full_name',
						render: function(data) {
                            return data ? data : "-";
                        }
					},
                    {
                        data: 'transfer',
                        name: 'transfer'
                    },
                    {
                        data: 'status',
                        name: 'status',
                        orderable: false,
						searchable: false
                    },
                    { data: 'action', name: 'action', orderable: false, searchable: false },
                ],
                buttons: [{
                        extend: 'excel',
                        filename: "{{App_Name()}} - {{__('label.sub_in_charge')}}",
                        exportOptions: {
                            columns: [0, 2, 3, 4]
                        },
                        customize: function(xlsx) {
                            var sheet = xlsx.xl.worksheets['sheet1.xml'];
                            $('row:first c', sheet).attr('s', '2');
                        },
                    },
                    {
                        extend: 'csv',
                        filename: "{{App_Name()}} - {{__('label.sub_in_charge')}}",
                        exportOptions: {
                            columns: [0, 2, 3, 4]
                        },
                    },
                    {
                        extend: 'pdf',
                        title: "{{App_Name()}} - {{__('label.sub_in_charge')}}",
                        filename: "{{App_Name()}} - {{__('label.sub_in_charge')}}",
                        pageSize: 'A4',
                        exportOptions: {
                            columns: [0, 2, 3, 4]
                        },
                        customize: function(doc) {
                            doc.styles.tableHeader.fontSize = 10;
                            doc.defaultStyle.fontSize = 8;
                            doc.content[1].table.widths = ['5%', '20%', '15%', '25%', '20%', '15%'];
                            doc.content[1].layout = "borders";
                            doc.styles.title.fontSize = 22;
                            doc.styles.title.alignment = 'center';
                            doc.defaultStyle.alignment = 'center';

                            // Create a header
                            doc['header'] = (function(page, pages) {
                                return {
                                    columns: [{
                                            alignment: 'left',
                                            bold: true,
                                            text: "{{App_Name()}}",
                                        },
                                        {
                                            alignment: 'right',
                                            bold: true,
                                            text: ['Total Page ', {
                                                text: pages.toString()
                                            }],
                                        }
                                    ],
                                    margin: [20, 20],
                                }
                            });
                            // Create a footer
                            doc['footer'] = (function(page, pages) {
                                return {
                                    columns: [{
                                        alignment: 'center',
                                        bold: true,
                                        text: ['Page ', {
                                            text: page.toString()
                                        }, ' of ', {
                                            text: pages.toString()
                                        }],
                                    }],
                                }
                            });
                        }
                    }
                ],
            });

            $('#ms_excel').on('click', function() {

                var Demo_Mode = '{{ Demo_Mode() }}';
                if(Demo_Mode == 1){
                    var table = $('#datatable').DataTable();
                    table.button('0').trigger();
                } else {
                    showError();
                }
            });
            $('#csv').on('click', function() {

                var Demo_Mode = '{{ Demo_Mode() }}';
                if(Demo_Mode == 1){
                    var table = $('#datatable').DataTable();
                    table.button('1').trigger();
                } else {
                    showError();
                }
            });
            $('#pdf').on('click', function() {

                var Demo_Mode = '{{ Demo_Mode() }}';
                if(Demo_Mode == 1){
                    var table = $('#datatable').DataTable();
                    table.button('2').trigger();
                } else {
                    showError();
                }
            });

            $('#input_status, #input_department').change(function() {
                table.draw();
            });
            $('#input_search').keyup(function() {
                table.draw();
            });
        });

        function change_status(id, status) {

            var Demo_Mode = '<?php echo Demo_Mode(); ?>';
            if(Demo_Mode == 1){

                $("#dvloader").show();
                var url = `{{ route('sub_incharge.show', '') }}/${id}`;

                $.ajax({
                    type: "GET",
                    url: url,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(resp) {
                        $("#dvloader").hide();

                        if (resp.status == 200) {
                            if (resp.status_code == 1) {
                                $('#' + id).text('{{__("label.active")}}').removeClass('hide-btn').addClass('show-btn');
                            } else {
                                $('#' + id).text('{{__("label.inactive")}}').removeClass('show-btn').addClass('hide-btn');
                            }
                            toastr.success(resp.success);
                        } else {
                            toastr.error(resp.errors);
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#dvloader").hide();
                        toastr.error(errorThrown, textStatus);
                    }
                });
            } else {
                showError();
            }
        };

        // make transfer
        $(document).on("click", ".in_charge_update", function() {

            var incharge_id = $(this).data('id');
            var departmentid = $(this).data('department_id');

            $(".modal-body #edit_incharge_id").val(incharge_id);
            $(".modal-body #edit_department_id").val(departmentid).trigger('change');
        });

        // Transfer 
        function in_charge_update() {

            var Check_Admin = '<?php echo Demo_Mode(); ?>';
            if (Check_Admin == 1) {

                $("#dvloader").show();
                var formData = new FormData($("#in_charge_update")[0]);
                $.ajax({
                    type: 'POST',
                    url: '{{ route("sub_incharge.transfer") }}',
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(resp) {
                        $("#dvloader").hide();
                        get_responce_message(resp, 'in_charge_update', '{{ route("sub_incharge.index") }}');
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#dvloader").hide();
                        toastr.error(errorThrown, textStatus);
                    }
                });
            } else {
                showError();
            }
        }

        // get service
		$('#edit_department_id').change(function() {
            var department_id = $(this).val();
            $.ajax({
                type: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: '{{ route("all_service") }}',
                data: {
                    departmentId: department_id
                },
                success: function(response) {
                    $('#service_id').empty();
                    $('#service_id').append('<option value="">Select Service</option>');
                    response.forEach(function(item) {

                        $('#service_id').append(`<option value="${item.id}">${item.name}</option>`);
                    });
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        });
    </script>
@endsection