@extends('layouts.app')
@section('meta')

@endsection
@section('title',config('app.name') . ' | ' . __('base/bank_reconciliation.document_title'))
@section('css_specific')
    <link href="{{ asset('gentelella/plugins/bootstrap-daterangepicker/daterangepicker.css') }}" rel="stylesheet"/>
@endsection
@section('css')

@endsection
@section('content')
    <div id="modals">

    </div>

    <!-- page content -->
    <div class="right_col" role="main">
        <div class="">

            <!-- Titulo -->
            <div class="page-title">
                <div class="title_left">
                    <h3>@lang('base/bank_reconciliation.document_title')</h3>
                </div>
                <div class="title_right text-right">
                    <div class="row">
                        <div class="col-md-5 col-xs-12 pull-right">
                            <a href="{{route('bank-reconciliations/download-template')}}"
                               class="btn btn-sm btn-success">@lang('general.button_download_template_import')
                            </a>
                            &nbsp;
                            <a href="{{route('bank-reconciliations.index')}}"
                               class="btn btn-sm btn-default">@lang('general.button_discard')
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /Titulo -->

            <div class="clearfix"></div>

            <!-- Mensajes -->
            <div id="general_messages">
                @include('flash::message')
                @if (!$errors->isEmpty())
                    <div class="alert alert-danger alert-dismissable alert-important" role="alert">
                        <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                        {{ __('general.error_form') }}
                    </div>
                @endif
            </div>
            <!-- /Mensajes -->

            <!-- Contenido -->
            <div class="row">
                <div class="col-md-12 col-xs-12">
                    <div class="x_panel">
                        <div class="x_title">
                            <h2>@lang('general.text_add')</h2>
                            <div class="clearfix"></div>
                        </div>
                        <div class="x_content">
                            {!! Form::open(['route' => 'bank-reconciliations.store','method' => 'POST','class' => '','role' => 'form','id'=>'form','files' => true]) !!}
                            <!-- input hidden -->
                            {!! Form::hidden('key', old('key','')) !!}
                            <input name="file_template_file" type="file" class="hidden"/>
                            <!-- /.input hidden -->
                            <div class="row mb-0">
                                <div class="col-md-6 col-md-offset-3 col-xs-12 text-center">
                                    <div class="form-group form-group-sm{{ $errors->has('name') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('name', __('base/bank_reconciliation.entry_name') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::text('name', old('name'), ['class' => 'form-control', 'placeholder' => __('base/bank_reconciliation.help_name'),'required','autofocus']) !!}
                                        @if ($errors->has('name'))
                                            <span class="help-block"><small>{{ $errors->first('name') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 col-xs-12">
                                    <hr>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 col-xs-12">
                                    <div class="row">
                                        <div class="col-md-12 col-xs-12 mt-0 text-center">
                                            <h4>@lang('base/bank_reconciliation.text_cfdi_downloads')</h4>
                                        </div>
                                    </div>
                                    <div class="row" style="min-height: 70px;">
                                        <div class="col-md-5 col-xs-12">
                                            <div class="form-group form-group-sm">
                                                {!! html_entity_decode(Form::label('filter_date_from', __('general.text_date_from') . '', ['class' => 'control-label'])) !!}
                                                <div class="input-group input-group-sm">
                                                    {!! Form::text('filter_date_from', request()->input('filter_date_from',\App\Helpers\Helper::date(Date::parse('first day of this month'))), ['class' => 'form-control', 'placeholder' => __('general.text_date_from'),'autocomplete'=>'off']) !!}
                                                    <span class="input-group-addon"><i
                                                            class="fa fa-calendar"></i></span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-5 col-xs-12">
                                            <div class="form-group form-group-sm">
                                                {!! html_entity_decode(Form::label('filter_date_to', __('general.text_date_to') . '', ['class' => 'control-label'])) !!}
                                                <div class="input-group input-group-sm">
                                                    {!! Form::text('filter_date_to', request()->input('filter_date_to',\App\Helpers\Helper::date(Date::parse('last day of this month'))), ['class' => 'form-control', 'placeholder' => __('general.text_date_to'),'autocomplete'=>'off']) !!}
                                                    <span class="input-group-addon"><i
                                                            class="fa fa-calendar"></i></span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-2 col-xs-12 text-center">
                                            <label class="control-lable">&nbsp;</label><br>
                                            {!! Form::button(__('general.button_search'),['type' => 'button', 'class' => 'btn btn-sm btn-default btn-block', 'id' => 'btn_search_cfdi_downloads']) !!}
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12 col-xs-12 mt-3">
                                            <div class="table-responsive table-data" id="data_cfdi_downloads"
                                                 style="height: 350px; border: 1px solid #eeeeee; overflow-y: scroll;">
                                                <table class="table table-striped table-hover table-condensed">
                                                    <thead>
                                                    <tr class="mini">
                                                        <th class="text-center" style="width: 30px;"></th>
                                                        <th class="text-center">@lang('base/bank_reconciliation.column_date')</th>
                                                        <th class="text-left">@lang('base/bank_reconciliation.column_name')</th>
                                                        <th class="text-center">@lang('base/bank_reconciliation.column_currency_code')</th>
                                                        <th class="text-center">@lang('base/bank_reconciliation.column_credit')</th>
                                                        <th class="text-center">@lang('base/bank_reconciliation.column_debit')</th>
                                                        <th class="text-center" style="width: 35px;"></th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-xs-12">
                                    <div class="row">
                                        <div class="col-md-12 col-xs-12 mt-0 text-center">
                                            <h4>@lang('base/bank_reconciliation.text_bank_moves')</h4>
                                        </div>
                                    </div>
                                    <div class="row" style="min-height: 70px;">
                                        <div class="col-md-12 col-xs-12 text-center">
                                            <label class="control-lable">&nbsp;</label><br>
                                            {!! Form::button(__('general.button_import'),['type' => 'button', 'class' => 'btn btn-sm btn-info', 'id' => 'btn_template_import']) !!}
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12 col-xs-12 mt-3">
                                            <div class="table-responsive table-data" id="data_template_import"
                                                 style="height: 350px; border: 1px solid #eeeeee; overflow-y: scroll;">
                                                <table class="table table-striped table-hover table-condensed">
                                                    <thead>
                                                    <tr class="mini">
                                                        <th class="text-center" style="width: 30px;"></th>
                                                        <th class="text-center">@lang('base/bank_reconciliation.column_date')</th>
                                                        <th class="text-left">@lang('base/bank_reconciliation.column_reference')</th>
                                                        <th class="text-center">@lang('base/bank_reconciliation.column_currency_code')</th>
                                                        <th class="text-center">@lang('base/bank_reconciliation.column_credit')</th>
                                                        <th class="text-center">@lang('base/bank_reconciliation.column_debit')</th>
                                                        <th class="text-center" style="width: 35px;"></th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row mt-5">
                                <div class="col-md-12 col-xs-12 text-center">
                                    <div id="general_messages_2" class="mb-2">
                                    </div>
                                </div>
                                <div class="col-md-12 col-xs-12 text-center">
                                    {!! Form::button(__('general.button_auto_reconciliation'),['type' => 'button', 'class' => 'btn btn-sm btn-info', 'id' => 'btn_auto_reconciliation']) !!}
                                    &nbsp;
                                    {!! Form::button(__('general.button_manual_reconciliation'),['type' => 'button', 'class' => 'btn btn-sm btn-info', 'id' => 'btn_manual_reconciliation']) !!}
                                    &nbsp;
                                    {!! Form::button(__('general.button_unreconcile'),['type' => 'button', 'class' => 'btn btn-sm btn-info', 'id' => 'btn_unreconcile']) !!}
                                    &nbsp;
                                    {!! Form::button(__('general.button_save'),['type' => 'button', 'class' => 'btn btn-sm btn-primary', 'id' => 'btn_save']) !!}
                                </div>
                            </div>
                            {!! Form::close() !!}

                            <!-- Footer form -->
                            <!-- /Footer form -->
                        </div><!-- /x_content -->
                    </div><!-- /x_panel -->
                </div>
            </div><!-- /Contenido -->

        </div>
    </div><!-- /page content -->
@endsection
@section('scripts_specific')
    <script src="{{ asset('gentelella/plugins/bootstrap-daterangepicker/daterangepicker.js') }}"></script>
@endsection
@section('scripts')
    <script type="text/javascript">

        /* Cargar plantilla  */
        function bankMoveTempTemplateImport() {
            $("#form #data_template_import tbody").html("");
            $("#form .reconciled_cfdi_download").html("");
            if(true){
                $.ajax({
                    url: "{{ route('bank-reconciliations/bank-move-temp-template-import') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: new FormData($("#form").get(0)),
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data.html) {
                            $("#form #data_template_import tbody").html(data.html);
                            $("#form input[name='key']").val(data.key);
                        }
                        $("#form input[name='file_template_file']").val("");
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                        $("#form input[name='file_template_file']").val("");
                    }
                });
            }
        }

        $(function () {
            /*Configura datepicker*/
            moment.locale("{{ substr(app()->getLocale(),0,2) }}");
            $("#form input[name='filter_date_from']").daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                locale: {
                    format: "{{ setting('date_picker_format','DD-MM-YYYY') }}"
                },
                autoUpdateInput: false
            }, function (chosen_date) {
                $("#form input[name='filter_date_from']").val(chosen_date.format("{{ setting('date_picker_format','DD-MM-YYYY') }}"));
            });
            $("#form input[name='filter_date_to']").daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                locale: {
                    format: "{{ setting('date_picker_format','DD-MM-YYYY') }}"
                },
                autoUpdateInput: false,
            }, function (chosen_date) {
                $("#form input[name='filter_date_to']").val(chosen_date.format("{{ setting('date_picker_format','DD-MM-YYYY') }}"));
            });
            /* Obtiene cfdis descargados */
            $("#form #btn_search_cfdi_downloads").on("click", function () {
                let filter_date_from = $("#form input[name='filter_date_from']").val();
                let filter_date_to = $("#form input[name='filter_date_to']").val();
                $("#form #data_cfdi_downloads tbody").html("");
                if(filter_date_from && filter_date_to){
                    $.ajax({
                        url: "{{ route('cfdi-downloads/per-reconciliation') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "filter_date_from=" + filter_date_from + "&filter_date_to=" + filter_date_to + "",
                        success: function (data) {
                            if (data.html) {
                                $("#form #data_cfdi_downloads tbody").html(data.html);
                            }
                        },
                        error: function (error, textStatus, errorThrown) {
                            if (error.status == 422) {
                                var message = error.responseJSON.error;
                                $("#general_messages").html(alertMessage("danger", message));
                            } else if (error.status == 403 || error.status == 401) {
                                location.href = "{{ route('login') }}";
                            } else {
                                alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                            }
                        }
                    });
                }
            }).trigger("click");

            $("#form #btn_template_import").on("click", function (e) {
                e.preventDefault();
                $("#form input[name='file_template_file']").trigger("click");
            });
            $("#form input[name='file_template_file']").change(function(e){
                e.target.files[0].name = e.target.files[0].name + Math.floor((Math.random() * 100) + 1);
                let fileName = e.target.files[0].name;
                $("#form #file_template_file_upload").text(fileName).addClass('label label-success font-14');
                bankMoveTempTemplateImport();
            });

            /*Conciliacion manual*/
            $("#form #btn_auto_reconciliation").on("click", function (e) {
                $("#general_messages_2").html("");
                $.ajax({
                    url: "{{ route('bank-reconciliations/bank-move-temp-auto-reconciled') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: new FormData($("#form").get(0)),
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        $('input[name*=\'selected_cfdi_download\']').prop('checked', false);
                        $('input[name*=\'selected_bank_move_temp\']').prop('checked', false);
                        $.each(data.selected_reconciliation_line, function (sort_order, data) {
                            $.each(data.selected_cfdi_download, function (key, value) {
                                $("#reconciled_cfdi_download_no_" + value).html(sort_order);
                            }, sort_order);
                            $.each(data.selected_bank_move_temp, function (key, value) {
                                $("#reconciled_bank_move_temp_no_" + value).html(sort_order);
                            }, sort_order);
                        });
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages_2").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            /*Desconsiliar manual*/
            $("#form #btn_unreconcile").on("click", function (e) {
                $("#general_messages_2").html("");
                $.ajax({
                    url: "{{ route('bank-reconciliations/bank-move-temp-manual-unreconciled') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: new FormData($("#form").get(0)),
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        $('input[name*=\'selected_cfdi_download\']').prop('checked', false);
                        $.each(data.selected_cfdi_download, function (key, value) {
                            $("#reconciled_cfdi_download_no_" + value).html("");
                        });
                        $('input[name*=\'selected_bank_move_temp\']').prop('checked', false);
                        $.each(data.selected_bank_move_temp, function (key, value) {
                            $("#reconciled_bank_move_temp_no_" + value).html("");
                        });
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages_2").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            /*Conciliacion manual*/
            $("#form #btn_manual_reconciliation").on("click", function (e) {
                $("#general_messages_2").html("");
                $.ajax({
                    url: "{{ route('bank-reconciliations/bank-move-temp-manual-reconciled') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: new FormData($("#form").get(0)),
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        $('input[name*=\'selected_cfdi_download\']').prop('checked', false);
                        $.each(data.selected_cfdi_download, function (key, value) {
                            $("#reconciled_cfdi_download_no_" + value).html(data.sort_order);
                        });
                        $('input[name*=\'selected_bank_move_temp\']').prop('checked', false);
                        $.each(data.selected_bank_move_temp, function (key, value) {
                            $("#reconciled_bank_move_temp_no_" + value).html(data.sort_order);
                        });
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages_2").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
            /*Conciliacion manual*/
            $("#form #btn_save").on("click", function (e) {
                $.ajax({
                    url: "{{ route('bank-reconciliations.store') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: new FormData($("#form").get(0)),
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        location.href = "{{ route('bank-reconciliations.index') }}";
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages").html(alertMessage("danger", message));
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            });
        });

    </script>
@endsection
