@extends('layouts.app-hr')

@section('content')
    <?php Fun::lang()?>
    @include('hr.holiday.import-excel')
    <style>
        td.details-control {
            background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center center;
            cursor: pointer;
        }
        tr.details td.details-control {
            background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center center;
        }
    </style>
    <div class="top-header">
        <ol class="breadcrumb">
            <li><a href="#">{{__('administrator.dashboard')}}</a></li>
            <li><a href="#">{{__('administrator.holiday')}}</a></li>
        </ol>
    </div>
    <div class="page">
        <div class="top-content">
            <div class="row">
                <div class="col-sm-6 col-xs-12">
                    <div class="title-add">
                        <div class="pull-left">
                            <h3>{{__('administrator.holiday')}} </h3>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6 col-xs-12">
                    <div class="title-add">
                        <div class="pull-right">
                            @if(Gate::check('Holiday Create'))
{{--                                <a href="{{route('hr-holiday.create')}}" class="button_primary">{{__('administrator.add_new')}}</a>--}}
                                <a href="#" class="button_primary btn_create_new">{{__('administrator.add_new')}}</a>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="box-body">
            <table id="datatable_products" width="100%" class="table table-striped">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>{{__('administrator.name')}}</th>
                        <th>{{__('administrator.year')}}</th>
                        <th>{{__('administrator.note')}}</th>
                        <th>{{__('administrator.created_at')}}</th>
                        <th style="width: 200px;">{{__('administrator.action') }}</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
@endsection
@section('script')
    <script type="text/javascript" src="{{asset('assets/js/handlebars.min.js')}}"></script>
    <script id="details-template" type="text/x-handlebars-template">
    @verbatim
            <table class="table table-blue" id="holidayDetail-{{id}}">
                <thead>
                    <tr>
                        <th class="text-center">No</th>
                        <th class="text-center">ថ្ងៃឈប់សម្រាក (ខ្មែរ)</th>
                        <th class="text-center">Holiday (English)</th>
                        <th class="text-center">From Date</th>
                        <th class="text-center">To Date</th>
                        <th class="text-center">Days</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
    @endverbatim
    </script>
    <script type="text/javascript">
        $(document).ready(function () {

        });

        var table = $('#datatable_products').DataTable({
            ordering: false,
            serverSide: true,
            ajax: "{{route('hr.get-holiday')}}",
            lengthMenu: [
                [20, 30, 50, 100, 1000],
                [20, 30, 50, 100, 1000]
            ],
            columns:
                [
                    {
                        "className": 'details-control',
                        "orderable": false,
                        "searchable": false,
                        "data": null,
                        "defaultContent": ''
                    },
                    {
                        data: 'name'
                    },
                    {
                        data: 'year'
                    },
                    {
                        data: 'note'
                    },
                    {
                        data: 'created_at'
                    },
                    {
                        data: 'action',
                        orderable: false,
                        searchable: false
                    },
                ],
            "initComplete": function (settings, json) {

            }
        });
        $.fn.dataTable.ext.errMode = 'throw';

        var template = Handlebars.compile($("#details-template").html());
        $(document).on('click', 'td.details-control', function () {

            var tr  = $(this).closest('tr');
            var row = table.row(tr);
            var tableId = 'holidayDetail-' + row.data().id;
            if (row.child.isShown()){
                row.child.hide();
                tr.removeClass('details');
            } else {
                row.child(template(row.data())).show();
                initDiv(tableId, row.data());
                tr.addClass('details');
            }
        });

        function initDiv(tableId, data) {
            $('#' + tableId).DataTable({
                paging: false,
                searching: false,
                ordering: false,
                info: false,
                ajax: data.details_url,
                columns: [
                    { data: 'DT_RowIndex' },
                    { data: 'name_kh' },
                    { data: 'name_en' },
                    { data: 'from_date' },
                    { data: 'to_date' },
                    { data: 'count_day' },
                    { data: 'action' },
                ],
                "initComplete": function (settings, json) {
                    $('.main-spinner').hide();
                }
            });
        }

        $(document).on('click', '.btn_create_new', function () {
            $.confirm({
                title: 'Create Holiday!',
                columnClass: 'xlarge',
                content: `
                <form action="" class="formName" id="myForm">
                    <div class="form-group col-md-6 col-sm-12">
                        <label class="required">Name</label>
                        <input type="text" name="name" placeholder="Name"  class="name form-control" autocomplete="off" />
                    </div>
                    <div class="form-group col-md-6 col-sm-12">
                        <label class="required">Year</label>
                        <input type="text" name="year" placeholder="Ex. 2000" class="name form-control number-only" maxlength="4"  autocomplete="off" />
                    </div>
                     <div class="form-group col-md-6 col-sm-12">
                        <label class="required">Effect Date</label>
                        <input type="text" name="effect_date" placeholder="Effect date" class="name form-control date_picker"  autocomplete="off" />
                    </div>
                    <div class="form-group col-md-6 col-sm-12">
                        <label>Note</label>
                        <input type="text" name="note" placeholder="Note" class="name form-control" autocomplete="off" />
                    </div>
                    <div class="form-group">
                        <table class="table table-striped" width="100%">
                            <thead>
                                <tr>
                                    <th><label>No</label></th>
                                    <th><label class="required">Name (KH)</label></th>
                                    <th><label class="required">Name (EN)</label></th>
                                    <th><label class="required">From Date</label></th>
                                    <th><label class="required">To Date</label></th>
                                    <th><a class="btn btn-sm btn-success btnAdd"><i class="fa fa-plus"></i> </a></th>
                                </tr>
                            </thead>
                            <tbody id="tbodyHoliday">
                                <tr>
                                    <td class="num">1</td>
                                    <td><input type="text" name="name_kh[]" class="form-control name_kh" /></td>
                                    <td><input type="text" name="name_en[]" class="form-control name_en" /></td>
                                    <td><input type="text" name="from_date[]" class="form-control date_picker" /></td>
                                    <td><input type="text" name="to_date[]" class="form-control date_picker" /></td>
                                    <td><a class="btn btn-sm btn-danger btnRemove"><i class="fa fa-times"></i> </a></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </form>`
                ,
                buttons: {
                    formSubmit: {
                        text: '{{__('administrator.submit')}}',
                        btnClass: 'btn-blue',
                        action: function () {
                            var formData = new FormData($('#myForm')[0]);
                            $.ajax({
                                url: '{{ route("hr-holiday.store") }}',
                                type: 'POST',
                                datatype: 'json',
                                data: formData,
                                async: false,
                                cache: false,
                                contentType: false,
                                processData: false,
                                success: function (response) {
                                    if(response.status === 200){
                                        $('#datatable_products').DataTable().ajax.reload();
                                        $(document).find('.close_form').trigger('click');
                                        showSuccessToast(response.message);
                                    }
                                },
                                error: function (xhr) {
                                    alertErrorFormController(xhr);
                                }
                            });
                            return false;
                        }
                    },
                    cancel: {
                        text     : '{{__('administrator.cancel')}}',
                        btnClass : 'btn-red close_form',
                        keys     : ['esc'],
                        action   : function () {

                        }
                    },
                },
                onContentReady: function () {
                    var jc = this;
                    jc.$content.find(".date_picker").datepicker({
                        format: 'dd-mm-yyyy',
                        todayHighlight: true,
                        autoclose: true,
                    });

                    this.$content.find('form').on('submit', function (e) {
                        e.preventDefault();
                        jc.$$formSubmit.trigger('click');
                    });
                }
            });
        });

        $(document).on('click', '.btnAdd', function () {
            let row = `
                    <tr>
                        <td class="num"></td>
                        <td><input type="text" name="name_kh[]" class="form-control name_kh" /></td>
                        <td><input type="text" name="name_en[]" class="form-control name_en" /></td>
                        <td><input type="text" name="from_date[]" class="form-control date_picker" /></td>
                        <td><input type="text" name="to_date[]" class="form-control date_picker" /></td>
                        <td><a class="btn btn-sm btn-danger btnRemove"><i class="fa fa-times"></i> </a></td>
                    </tr>
            `;
            $('#tbodyHoliday').append(row);
            $(".date_picker").datepicker({
                format: 'dd-mm-yyyy',
                todayHighlight: true,
                autoclose: true,
            });
            autoNumber();
        });
        $(document).on('click', '.btnRemove', function () {
            $(this).closest('tr').remove();
            autoNumber();
        });

        function autoNumber(){
            $('.num').each(function (i, v) {
                $(this).text(i+1);
            });
        }

        $(document).on('click', '.btn_add_holiday', function () {
            let year    = $(this).data('year');
            let route   = '{{ route("add.holiday") }}';
            formHoliday({title : 'Add Holiday', route, year});

        });

        $(document).on('click', '.btn_edit_one', function () {
            let id = $(this).data('id');
            let route = '{{ route("update.holiday") }}';
            formHoliday({title: 'Edit Holiday', route, id});

        });

        function formHoliday({title = '', route = '', year = 2000, id = ''} = {}){
            $.confirm({
                title: title,
                columnClass: 'medium',
                content: `
                    <form action="" class="formName" id="formSerial">
                        <div class="form-group">
                            <label class="required">Name (KH)</label>
                            <input type="text" name="name_kh" placeholder="Name (KH)" class="form-control" autocomplete="off" />
                        </div>
                        <div class="form-group">
                            <label class="required">Name (EN)</label>
                            <input type="text" name="name_en" placeholder="Name (EN)" class="form-control" autocomplete="off" />
                        </div>
                        <div class="form-group">
                            <label class="required">From Date</label>
                            <input type="text" name="from_date" placeholder="From Date" class="form-control date_picker" autocomplete="off" />
                        </div>
                        <div class="form-group">
                            <label class="required">To Date</label>
                            <input type="text" name="to_date" placeholder="To Date" class="form-control date_picker" autocomplete="off" />
                        </div>
                    </form>`,
                buttons: {
                    formSubmit: {
                        text: '{{__('administrator.submit')}}',
                        btnClass: 'btn-blue',
                        action: function () {
                            var dataString = $("#formSerial").serialize();
                            $.ajax({
                                url: route,
                                type: 'POST',
                                datatype: 'json',
                                data: id ? dataString +'&id='+id : dataString +'&year='+year,
                                success: function (response) {
                                    if(response.status === 200){
                                        $('#datatable_products').DataTable().ajax.reload();
                                        $(document).find('.close_form').trigger('click');
                                        showSuccessToast(response.message);
                                    }
                                },
                                error: function (xhr) {
                                    alertErrorFormController(xhr);
                                }
                            });

                            return false;
                        }
                    },
                    cancel: {
                        text     : '{{__('administrator.cancel')}}',
                        btnClass : 'btn-red close_form',
                        keys     : ['esc'],
                        action   : function () {

                        }
                    },
                },
                onContentReady: function () {
                    var jc = this;
                    jc.$content.find(".date_picker").datepicker({
                        format: 'dd-mm-yyyy',
                        todayHighlight: true,
                        autoclose: true,
                    });

                    this.$content.find('form').on('submit', function (e) {
                        e.preventDefault();
                        jc.$$formSubmit.trigger('click');
                    });
                }
            });

            if(id){
                let url = "{{ route('hr-holiday.edit',['hid']) }}";
                url = url.replace('hid', id);
                $.get(url, function (data) {
                    setTimeout(function () {
                        $(document).find('input[name=name_kh]').val(data.name_kh);
                        $(document).find('input[name=name_en]').val(data.name_en);
                        $(document).find('input[name=from_date]').val(formatDate(data.from_date));
                        $(document).find('input[name=to_date]').val(formatDate(data.to_date));
                    });
                });
            }
        }

        function formatDate(date){
            const items = date.split('-');
            return items[2]+'-'+items[1]+'-'+items[0];
        }

        $(document).on('click', '.btn_delete_one', function () {
            let id = $(this).data('id');
            $.confirm({
                title: 'Confirm!',
                content: 'Are you sur to delete this record!',
                buttons: {
                    confirm: {
                        text : '{{ __('administrator.confirm') }}',
                        btnClass: 'btn-blue',
                        action: function () {
                            $.ajax({
                                url: '{{ route("delete-holiday") }}',
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    _token: '{{ csrf_token() }}',
                                    id: id
                                }
                            }).done(function (response) {
                                if(response.status === 200){
                                    $('#datatable_products').DataTable().ajax.reload();
                                    showSuccessToast(response.message);
                                }

                            }).fail(function (xhr) {
                                alertErrorFormController(xhr);
                            });
                        }
                    },
                    cancel: {
                        text : '{{ __('administrator.cancel') }}',
                        btnClass: 'btn-red',
                        action: function () {

                        }
                    },
                }
            });
        });

        $(document).on('click', '.btn_edit', function () {

        });

        $(document).on('click', '.btn_del_holiday', function () {

        });
    </script>
@endsection
