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

@endsection
@section('title',config('app.name') . ' | ' . __('sales/customer_payment.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('sales/customer_payment.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('customer-payments.index',request()->except('page'))}}"
                               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' => 'customer-payments.store','method' => 'POST','class' => '','role' => 'form','id'=>'form']) !!}
                            <!-- input hidden -->
                            {!! Form::hidden('amount_reconciled', old('amount_reconciled',0)) !!}
                            <div class="hidden">
                                <input type="file" name="file_add_xml">
                            </div>
                            <!-- /.input hidden -->
                            <div class="row">
                            @if($tax_regimens->isNotEmpty())
                                <div class="col-md-6 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('tax_regimen_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('tax_regimen_id', __('sales/customer_payment.entry_tax_regimen_id') . '', ['class' => 'control-label'])) !!}
                                        {!! Form::select('tax_regimen_id', $tax_regimens,old('tax_regimen_id',($duplicate_ci->tax_regimen_id ?? \App\Helpers\Helper::defaultCompany()->tax_regimen_id)), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                        @if ($errors->has('tax_regimen_id'))
                                            <span class="help-block"><small>{{ $errors->first('tax_regimen_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                            @endif
                            </div>
                            <div class="row">
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('date') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('date', __('sales/customer_payment.entry_date') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        <div class="input-group input-group-sm">
                                            {!! Form::text('date', old('date',\App\Helpers\Helper::dateTime(Date::now())), ['class' => 'form-control', 'placeholder' => __('sales/customer_payment.entry_date'),'required','autocomplete'=>'off']) !!}
                                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                        </div>
                                        @if ($errors->has('date'))
                                            <span class="help-block"><small>{{ $errors->first('date') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('date_payment') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('date_payment', __('sales/customer_payment.entry_date_payment') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        <div class="input-group input-group-sm">
                                            {!! Form::text('date_payment', old('date_payment',\App\Helpers\Helper::dateTime(Date::now())), ['class' => 'form-control', 'placeholder' => __('sales/customer_payment.entry_date_payment'),'required','autocomplete'=>'off']) !!}
                                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                        </div>
                                        @if ($errors->has('date_payment'))
                                            <span class="help-block"><small>{{ $errors->first('date_payment') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('company_bank_account_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('company_bank_account_id', __('sales/customer_payment.entry_company_bank_account_id') . ' ', ['class' => 'control-label'])) !!}
                                        {!! Form::select('company_bank_account_id', $company_bank_accounts,old('company_bank_account_id',($duplicate_ci->company_bank_account_id ?? '')), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                        @if ($errors->has('company_bank_account_id'))
                                            <span class="help-block"><small>{{ $errors->first('company_bank_account_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm">
                                        {!! html_entity_decode(Form::label('reference', __('sales/customer_payment.entry_reference') . '', ['class' => 'control-label'])) !!}
                                        {!! Form::text('reference', old('reference',($duplicate_ci->reference ?? '')), ['class' => 'form-control', 'placeholder' => __('sales/customer_payment.entry_reference'),'autocomplete'=>'off']) !!}
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('customer_id') ? ' has-error' : '' }}">
                                        @php
                                            $tmp_customers = [];
                                            $tmp_customer_bank_accounts = [];
                                            if(!empty(old('customer_id',($duplicate_ci->customer_id ?? '')))){
                                                $tmp = \App\Models\Sales\Customer::where('id',old('customer_id',($duplicate_ci->customer_id ?? '')))->get();
                                                $tmp_customers = $tmp->pluck('text_select2','id');
                                                $tmp_customer_bank_accounts = $tmp->first()->customerActiveBankAccounts->pluck('name','id');
                                            }
                                        @endphp
                                        {!! html_entity_decode(Form::label('customer_id', __('sales/customer_payment.entry_customer_id')  . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        <div class="input-group input-group-sm">
                                            {!! Form::select('customer_id', $tmp_customers,old('customer_id',($duplicate_ci->customer_id ?? '')), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                            <span class="input-group-btn">
                                                <button type="button" class="btn btn-info btn-customer-search"><i class="fa fa-search"></i></button>
                                            </span>
                                        </div>
                                        @if ($errors->has('customer_id'))
                                            <span class="help-block"><small>{{ $errors->first('customer_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('tax_regimen_customer_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('tax_regimen_customer_id', __('sales/customer_payment.entry_tax_regimen_customer_id') . '', ['class' => 'control-label'])) !!}
                                        {!! Form::select('tax_regimen_customer_id', $tax_regimen_customers,old('tax_regimen_customer_id',($duplicate_ci->tax_regimen_customer_id ?? '')), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                        @if ($errors->has('tax_regimen_customer_id'))
                                            <span class="help-block"><small>{{ $errors->first('tax_regimen_customer_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('payment_way_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('payment_way_id', __('sales/customer_payment.entry_payment_way_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('payment_way_id', $payment_ways,old('payment_way_id',($duplicate_ci->payment_way_id ?? '')), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('payment_way_id'))
                                            <span class="help-block"><small>{{ $errors->first('payment_way_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('customer_bank_account_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('customer_bank_account_id', __('sales/customer_payment.entry_customer_bank_account_id') . ' ', ['class' => 'control-label'])) !!}
                                        {!! Form::select('customer_bank_account_id', $tmp_customer_bank_accounts,old('customer_bank_account_id',($duplicate_ci->customer_bank_account_id ?? '')), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                        @if ($errors->has('customer_bank_account_id'))
                                            <span class="help-block"><small>{{ $errors->first('customer_bank_account_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('branch_office_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('branch_office_id', __('sales/customer_payment.entry_branch_office_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('branch_office_id', $branch_offices,old('branch_office_id',($duplicate_ci->branch_office_id ?? \App\Models\Base\BranchOffice::where('company_id','=',\App\Helpers\Helper::defaultCompany()->id)->get()->first()->id)), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('branch_office_id'))
                                            <span class="help-block"><small>{{ $errors->first('branch_office_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-2 col-xs-7">
                                    <div class="form-group form-group-sm{{ $errors->has('currency_id') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('currency_id', __('sales/customer_payment.entry_currency_id') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::select('currency_id', $currencies,old('currency_id',($duplicate_ci->currency_id ?? \App\Models\Catalogs\Currency::first()->id)), ['class' => 'form-control', 'placeholder' => __('general.text_select'),'required']) !!}
                                        @if ($errors->has('currency_id'))
                                            <span class="help-block"><small>{{ $errors->first('currency_id') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-1 col-xs-5">
                                    <div class="form-group form-group-sm{{ $errors->has('currency_value') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('currency_value', __('sales/customer_payment.entry_currency_value') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::number('currency_value', old('currency_value'), ['class' => 'form-control text-center', 'placeholder' => __('sales/customer_payment.entry_currency_value'),'required','step' => 'any']) !!}
                                        @if ($errors->has('currency_value'))
                                            <span class="help-block"><small>{{ $errors->first('currency_value') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('amount') ? ' has-error' : '' }}">
                                        {!! html_entity_decode(Form::label('amount', __('sales/customer_payment.entry_amount') . ' <span class="required text-danger">*</span>', ['class' => 'control-label'])) !!}
                                        {!! Form::number('amount', old('amount',round($duplicate_ci->amount ?? 0, 2)), ['class' => 'form-control text-right', 'placeholder' => __('sales/customer_payment.entry_amount'),'required', 'step' => 'any', 'autocomplete' => 'off']) !!}
                                        @if ($errors->has('amount'))
                                            <span class="help-block"><small>{{ $errors->first('amount') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3 col-xs-12">
                                    <div class="form-group form-group-sm">
                                        {!! html_entity_decode(Form::label('cfdi', __('sales/customer_payment.entry_cfdi') , ['class' => 'control-label'])) !!}
                                        <br/>
                                        <label>
                                            {!! Form::checkbox('cfdi', '1',(!empty(old('cfdi',($duplicate_ci->cfdi ?? true))) ? true : false),['class' => 'js-switch']); !!}
                                        </label>
                                    </div>
                                </div>
                                @if(!empty(setting('enabled_projects')))
                                    <div class="col-md-3 col-xs-12">
                                        <div class="form-group form-group-sm{{ $errors->has('project_id') ? ' has-error' : '' }}">
                                            {!! html_entity_decode(Form::label('project_id', __('sales/customer_lease.entry_project_id') . '', ['class' => 'control-label'])) !!}
                                            {!! Form::select('project_id', $projects,old('project_id',($duplicate_ci->project_id ?? '')), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                            @if ($errors->has('project_id'))
                                                <span class="help-block"><small>{{ $errors->first('project_id') }}</small></span>
                                            @endif
                                        </div>
                                    </div>
                                @endif
                            </div>
                            <div class="row">
                                <div class="col-md-12 col-xs-12">
                                    <div class="form-group form-group-sm{{ $errors->has('item') ? ' has-error' : '' }}"
                                         style="margin-top: 20px;">
                                        @if ($errors->has('item'))
                                            <span class="help-block"><small>{{ $errors->first('item') }}</small></span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="" role="tabpanel" data-example-id="togglable-tabs">
                                <ul id="myTab" class="nav nav-tabs bar_tabs" role="tablist">
                                    <li role="presentation" class="active">
                                        <a href="#tab_reconcileds" id="reconcileds-tab" role="tab" data-toggle="tab"
                                           aria-expanded="true">@lang('sales/customer_payment.tab_reconcileds')</a>
                                    </li>
                                    <li role="presentation" class="">
                                        <a href="#tab_manual_reconcileds" id="manual-reconcileds-tab" role="tab" data-toggle="tab"
                                           aria-expanded="true">@lang('sales/customer_payment.tab_manual_reconcileds')</a>
                                    </li>
                                    <li role="presentation" class="">
                                        <a href="#tab_spei" id="spei-tab" role="tab"
                                           data-toggle="tab"
                                           aria-expanded="false">@lang('sales/customer_payment.tab_spei')</a>
                                    </li>
                                    <li role="presentation" class="">
                                        <a href="#tab_relations" id="relations-tab" role="tab"
                                           data-toggle="tab"
                                           aria-expanded="false">@lang('sales/customer_payment.tab_relations')</a>
                                    </li>
                                </ul>
                                <div id="myTabContent" class="tab-content">
                                    <div role="tabpanel" class="tab-pane fade active in" id="tab_reconcileds"
                                         aria-labelledby="reconcileds-tab">
                                        <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <div class="well alert-important" style="margin: 10px 0 20px 0; padding: 5px 19px;">
                                                    <p class="text-center" style="margin: 0;">
                                                        @lang('sales/customer_payment.entry_amount'): <span id="reconciled_txt_amount"></span>
                                                        &nbsp;&nbsp;&nbsp;
                                                        @lang('sales/customer_payment.text_reconciled'): <span id="reconciled_txt_amount_reconciled"></span>
                                                        &nbsp;&nbsp;&nbsp;
                                                        @lang('sales/customer_payment.text_per_reconciled'): <span id="reconciled_txt_amount_per_reconciled"></span>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <p>
                                                    * @lang('sales/customer_payment.help_payment_reconciled')
                                                </p>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <div class="table-responsive">
                                                    <table class="table table-items table-condensed table-hover table-bordered table-striped"
                                                           id="items_reconciled">
                                                        <thead>
                                                        <tr>
                                                            <th class="text-center">@lang('sales/customer_payment.column_reconciled_name')</th>
                                                            <th width="15%" class="text-center">@lang('sales/customer_payment.column_reconciled_date')</th>
                                                            <th width="13%" class="text-center">@lang('sales/customer_payment.column_reconciled_date_due')</th>
                                                            <th width="10%" class="text-center">@lang('sales/customer_payment.column_reconciled_payment_method')</th>
                                                            <th width="8%" class="text-center">@lang('sales/customer_payment.column_reconciled_currency')</th>
                                                            <th width="12%" class="text-center">
                                                                @lang('sales/customer_payment.column_reconciled_amount_total')
                                                            </th>
                                                            <th width="12%" class="text-center">
                                                                @lang('sales/customer_payment.column_reconciled_balance')
                                                                <span id="info_reconciled_balance_currency"></span>
                                                            </th>
                                                            <th width="10%" class="text-center">@lang('sales/customer_payment.column_reconciled_currency_value')</th>
                                                            <th width="14%" class="text-center">@lang('sales/customer_payment.column_reconciled_amount_reconciled')</th>
                                                        </tr>
                                                        </thead>
                                                        <tbody>
                                                        <!-- Items -->
                                                        @php
                                                            $item_reconciled_row = 1;
                                                            $items_reconciled = (empty(old('item_reconciled')) ? [] : old('item_reconciled'));
                                                        @endphp
                                                        @foreach ($items_reconciled as $item_reconciled_row => $item)
                                                            @php
                                                                $tmp_name = '';
                                                                $tmp_date = '';
                                                                $tmp_date_due = '';
                                                                $tmp_currency_code = '';
                                                                $tmp_amount_total = '';
                                                                $tmp_balance = '';
                                                                if(!empty(old('item_reconciled.' . $item_reconciled_row . '.reconciled_id'))){
                                                                    $tmp_currency = \App\Models\Catalogs\Currency::find(old('currency_id'));
                                                                    $tmp = \App\Models\Sales\CustomerInvoice::find(old('item_reconciled.' . $item_reconciled_row . '.reconciled_id'));
                                                                    $tmp_name =!empty($tmp) ? $tmp->name : '';
                                                                    $tmp_date = !empty($tmp) ? \App\Helpers\Helper::convertSqlToDateTime($tmp->date) : '';
                                                                    $tmp_date_due = !empty($tmp) ? \App\Helpers\Helper::convertSqlToDate($tmp->date_due) : '';
                                                                    $tmp_payment_method = !empty($tmp) ? $tmp->paymentMethod->code : '';
                                                                    $tmp_currency_code = !empty($tmp) ? $tmp->currency->code : '';
                                                                    $tmp_amount_total = !empty($tmp) ? money($tmp->amount_total,$tmp->currency->code,true) : '';
                                                                    $tmp_balance = '<span id="item_reconciled_txt_balance_'. $item_reconciled_row .'">'. money(\App\Helpers\Helper::convertBalanceCurrency($tmp_currency,$tmp->balance,$tmp->currency->code,old('item_reconciled.' . $item_reconciled_row . '.currency_value')),$tmp->currency->code,true).'</span>';
                                                                }
                                                            @endphp
                                                            <tr id="item_reconciled_row_{{ $item_reconciled_row }}">
                                                                <td class="text-center align-middle" style="vertical-align: middle;">
                                                                    <!-- input hidden -->
                                                                    <input type="hidden" id="item_reconciled_id_{{ $item_reconciled_row }}"
                                                                           name="item_reconciled[{{ $item_reconciled_row }}][id]"
                                                                           value="{{ old('item_reconciled.' . $item_reconciled_row . '.id') }}">
                                                                    <input type="hidden" id="item_reconciled_reconciled_id_{{ $item_reconciled_row }}"
                                                                           name="item_reconciled[{{ $item_reconciled_row }}][reconciled_id]"
                                                                           value="{{ old('item_reconciled.' . $item_reconciled_row . '.reconciled_id') }}">
                                                                    <input type="hidden" id="item_reconciled_name_{{ $item_reconciled_row }}"
                                                                           name="item_reconciled[{{ $item_reconciled_row }}][name]"
                                                                           value="{{ old('item_reconciled.' . $item_reconciled_row . '.name') }}">
                                                                    <input type="hidden" id="item_reconciled_balance_{{ $item_reconciled_row }}"
                                                                           name="item_reconciled[{{ $item_reconciled_row }}][balance]"
                                                                           value="{{ old('item_reconciled.' . $item_reconciled_row . '.balance') }}">
                                                                    <input type="hidden" id="item_reconciled_currency_code_{{ $item_reconciled_row }}"
                                                                           name="item_reconciled[{{ $item_reconciled_row }}][currency_code]"
                                                                           value="{{ old('item_reconciled.' . $item_reconciled_row . '.currency_code') }}">
                                                                    <!-- /.input hidden -->
                                                                    {{$tmp_name}}
                                                                </td>
                                                                <td class="text-center align-middle">{{$tmp_date}}</td>
                                                                <td class="text-center align-middle">{{$tmp_date_due}}</td>
                                                                <td class="text-center align-middle">{{$tmp_payment_method}}</td>
                                                                <td class="text-center align-middle">{{$tmp_currency_code}}</td>
                                                                <td class="text-right align-middle">{{$tmp_amount_total}}</td>
                                                                <td class="text-right align-middle">{!!$tmp_balance!!}</td>
                                                                <td class="text-center align-middle">
                                                                    @if(!empty($tmp_currency) && $tmp_currency->code == 'MXN' && $tmp->currency->code != 'MXN')
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_reconciled.'.$item_reconciled_row.'.currency_value') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item_reconciled[' . $item_reconciled_row . '][currency_value]', old('item_reconciled.' . $item_reconciled_row . '.currency_value'), ['class' => 'form-control input-sm text-center col-currency-value', 'required','id' => 'item_reconciled_currency_value_' . $item_reconciled_row, 'step' => 'any']) !!}
                                                                        @if ($errors->has('item_reconciled.'.$item_reconciled_row.'.currency_value'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_reconciled.'.$item_reconciled_row.'.currency_value') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                    @else
                                                                        ---
                                                                    @endif
                                                                </td>
                                                                <td class="text-right align-middle">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_reconciled.'.$item_reconciled_row.'.amount_reconciled') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item_reconciled[' . $item_reconciled_row . '][amount_reconciled]', old('item_reconciled.' . $item_reconciled_row . '.amount_reconciled'), ['class' => 'form-control input-sm text-right col-amount-reconciled','id' => 'item_reconciled_amount_reconciled_' . $item_reconciled_row, 'step' => 'any']) !!}
                                                                        @if ($errors->has('item_reconciled.'.$item_reconciled_row.'.amount_reconciled'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_reconciled.'.$item_reconciled_row.'.amount_reconciled') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        @endforeach
                                                        @php
                                                            $item_reconciled_row++;
                                                        @endphp
                                                        <!-- /Items -->
                                                        <!-- Agregar nuevo item -->
                                                        <!-- Totales -->
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div role="tabpanel" class="tab-pane fade" id="tab_manual_reconcileds" aria-labelledby="manual-reconcileds-tab">
                                         @if(setting('cfdi_version') == 'cfdi40')
                                         <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <p class="">
                                                    @lang('sales/customer_payment.help_manual_reconcileds')<br/>
                                                   @lang('sales/customer_payment.help_manual_reconcileds2')<br/>
                                                   @lang('sales/customer_payment.help_manual_reconcileds3')
                                                </p>
                                            </div>
                                         </div>
                                         @endif
                                        <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <div class="table-responsive">
                                                    <table class="table table-items table-condensed table-hover table-bordered table-striped"
                                                           id="items_manual_reconciled" style="min-width: 1700px;">
                                                        <thead>
                                                        <tr>
                                                            <th width="5%" class="text-center">@lang('general.column_actions')</th>
                                                            <th class="text-center">@lang('sales/customer_payment.column_reconciled_uuid')<span class="required text-danger">*</span></th>
                                                            <th width="5%" class="text-center">@lang('sales/customer_payment.column_reconciled_serie')</th>
                                                            <th width="5%" class="text-center">@lang('sales/customer_payment.column_reconciled_folio')</th>
                                                            <th width="9%" class="text-center">@lang('sales/customer_payment.column_reconciled_currency')<span class="required text-danger">*</span></th>
                                                            <th width="5%" class="text-center">@lang('sales/customer_payment.column_reconciled_currency_value')</th>
                                                            <th width="11%" class="text-center">@lang('sales/customer_payment.column_reconciled_payment_method')<span class="required text-danger">*</span></th>
                                                            <th width="17%" class="text-center">{!! __('sales/customer_payment.column_reconciled_taxes') !!}</th>
                                                            <th width="6%" class="text-center">@lang('sales/customer_payment.column_reconciled_amount_total')<span class="required text-danger">*</span></th>
                                                            <th width="5%" class="text-center">@lang('sales/customer_payment.column_reconciled_number_of_payment')<span class="required text-danger">*</span></th>
                                                            <th width="6%" class="text-center">@lang('sales/customer_payment.column_reconciled_last_balance')<span class="required text-danger">*</span></th>
                                                            <th width="6%" class="text-center">@lang('sales/customer_payment.column_reconciled_amount_reconciled2')<span class="required text-danger">*</span></th>
                                                            <th width="6%" class="text-center">@lang('sales/customer_payment.column_reconciled_currenct_balance')<span class="required text-danger">*</span></th>
                                                        </tr>
                                                        </thead>
                                                        <tbody>
                                                        <!-- Items -->
                                                        @php
                                                            $item_manual_reconciled_row = 1;
                                                            $items_manual_reconciled = (empty(old('item_manual_reconciled')) ? ($duplicate_ci->customerActiveManualPaymentReconcileds ?? []) : old('item_manual_reconciled'));

                                                        @endphp
                                                        @foreach ($items_manual_reconciled as $item_manual_reconciled_row => $item)
                                                            @php
                                                                $item = !empty(old('item_manual_reconciled.' . $item_manual_reconciled_row . '')) ? (object) old('item_manual_reconciled.' . $item_manual_reconciled_row) : $item;
                                                            @endphp
                                                            <tr id="item_manual_reconciled_row_{{ $item_manual_reconciled_row }}">
                                                                <td class="text-center" style="vertical-align: middle;">
                                                                    <button type="button"
                                                                            onclick="$('#item_manual_reconciled_row_{{ $item_manual_reconciled_row }}').remove();"
                                                                            class="btn btn-xs btn-danger"
                                                                            style="margin-bottom: 0;">
                                                                        <i class="fa fa-trash"></i>
                                                                    </button>
                                                                    <!-- input hidden -->
                                                                    <input type="hidden" id="item_manual_reconciled_id_{{ $item_manual_reconciled_row }}"
                                                                           name="item_manual_reconciled[{{ $item_manual_reconciled_row }}][id]"
                                                                           value="{{ old('item_manual_reconciled.' . $item_manual_reconciled_row . '.id') }}">
                                                                    <!-- /.input hidden -->
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.uuid_related') ? ' has-error' : '' }}">
                                                                        {!! Form::text('item_manual_reconciled[' . $item_manual_reconciled_row . '][uuid_related]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.uuid_related',$item->uuid_related), ['class' => 'form-control input-sm text-center col-manual-uuid-related','id' => 'item_manual_reconciled_uuid_related_' . $item_manual_reconciled_row,'required', 'data-row' => $item_manual_reconciled_row]) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.uuid_related'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.uuid_related') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.serie_related') ? ' has-error' : '' }}">
                                                                        {!! Form::text('item_manual_reconciled[' . $item_manual_reconciled_row . '][serie_related]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.serie_related',$item->serie_related), ['class' => 'form-control input-sm text-center col-serie-related','id' => 'item_manual_reconciled_serie_related_' . $item_manual_reconciled_row]) !!}
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.folio_related') ? ' has-error' : '' }}">
                                                                        {!! Form::text('item_manual_reconciled[' . $item_manual_reconciled_row . '][folio_related]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.folio_related',$item->folio_related), ['class' => 'form-control input-sm text-center col-folio-related','id' => 'item_manual_reconciled_folio_related_' . $item_manual_reconciled_row]) !!}
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.currency_code_related') ? ' has-error' : '' }}">
                                                                        {!! Form::select('item_manual_reconciled[' . $item_manual_reconciled_row . '][currency_code_related]', $currency_codes, old('item_manual_reconciled.' . $item_manual_reconciled_row . '.currency_code_related',$item->currency_code_related), ['class' => 'form-control input-sm text-center col-currency-code-related','id' => 'item_manual_reconciled_currency_code_related_' . $item_manual_reconciled_row, 'placeholder' => __('general.text_select'),'required']) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.currency_code_related'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.currency_code_related') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.currency_value') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][currency_value]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.currency_value',!empty($item->currency_value) ? round($item->currency_value,4) : ''), ['class' => 'form-control input-sm text-center col-currency_value','id' => 'item_manual_reconciled_currency_value_' . $item_manual_reconciled_row, 'step' => 'any']) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.currency_value'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.currency_value') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.payment_method_code_related') ? ' has-error' : '' }}">
                                                                        {!! Form::select('item_manual_reconciled[' . $item_manual_reconciled_row . '][payment_method_code_related]', $payment_method_codes, old('item_manual_reconciled.' . $item_manual_reconciled_row . '.payment_method_code_related',$item->payment_method_code_related), ['class' => 'form-control input-sm text-center col-payment-method-code-related','id' => 'item_manual_reconciled_payment_method_code_related_' . $item_manual_reconciled_row, 'placeholder' => __('general.text_select'),'required']) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.payment_method_code_related'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.payment_method_code_related') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-left">
                                                                    <table>
                                                                        <tr class="col-taxes-{{ $item_manual_reconciled_row }}">
                                                                            <td style="width:50%; padding: 0 0 3px 0;">
                                                                                {!! Form::select('item_manual_reconciled[' . $item_manual_reconciled_row . '][tax_id_1]', $taxes,old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_1',$item->tax_id_1), ['class' => 'form-control input-sm','placeholder' => __('general.text_select'), 'id' => 'item_manual_reconciled_tax_id_1_' . $item_manual_reconciled_row]) !!}
                                                                            </td>
                                                                            <td style="padding: 0 0 3px 0;">
                                                                                {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][amount_base_1]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.amount_base_1', round($item->amount_base_1, 2)), ['class' => 'form-control input-sm text-right','id' => 'item_manual_reconciled_amount_base_1_' . $item_manual_reconciled_row, 'placeholder' => __('sales/customer_payment.column_reconciled_amount_base'), 'step' => 'any']) !!}
                                                                            </td>
                                                                        </tr>
                                                                        <tr class="col-taxes-{{ $item_manual_reconciled_row }} {{ !empty(old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_2',$item->tax_id_2)) ? '' : 'hidden' }}">
                                                                            <td style="width:50%; padding: 0 0 3px 0;">
                                                                                {!! Form::select('item_manual_reconciled[' . $item_manual_reconciled_row . '][tax_id_2]', $taxes,old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_2',$item->tax_id_2), ['class' => 'form-control input-sm','placeholder' => __('general.text_select'), 'id' => 'item_manual_reconciled_tax_id_2_' . $item_manual_reconciled_row]) !!}
                                                                            </td>
                                                                            <td style="padding: 0 0 3px 0;">
                                                                                {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][amount_base_2]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.amount_base_2', round($item->amount_base_2, 2)), ['class' => 'form-control input-sm text-right','id' => 'item_manual_reconciled_amount_base_2_' . $item_manual_reconciled_row, 'placeholder' => __('sales/customer_payment.column_reconciled_amount_base'), 'step' => 'any']) !!}
                                                                            </td>
                                                                        </tr>
                                                                        <tr class="col-taxes-{{ $item_manual_reconciled_row }} {{ !empty(old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_3',$item->tax_id_3)) ? '' : 'hidden' }}">
                                                                            <td style="width:50%; padding: 0 0 3px 0;">
                                                                                {!! Form::select('item_manual_reconciled[' . $item_manual_reconciled_row . '][tax_id_3]', $taxes,old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_3',$item->tax_id_3), ['class' => 'form-control input-sm','placeholder' => __('general.text_select'), 'id' => 'item_manual_reconciled_tax_id_3_' . $item_manual_reconciled_row]) !!}
                                                                            </td>
                                                                            <td style="padding: 0 0 3px 0;">
                                                                                {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][amount_base_3]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.amount_base_3', round($item->amount_base_3, 2)), ['class' => 'form-control input-sm text-right','id' => 'item_manual_reconciled_amount_base_3_' . $item_manual_reconciled_row, 'placeholder' => __('sales/customer_payment.column_reconciled_amount_base'), 'step' => 'any']) !!}
                                                                            </td>
                                                                        </tr>
                                                                        <tr class="col-taxes-{{ $item_manual_reconciled_row }} {{ !empty(old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_4',$item->tax_id_4)) ? '' : 'hidden' }}">
                                                                            <td style="width:50%; padding: 0 0 3px 0;">
                                                                                {!! Form::select('item_manual_reconciled[' . $item_manual_reconciled_row . '][tax_id_4]', $taxes,old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_4',$item->tax_id_4), ['class' => 'form-control input-sm','placeholder' => __('general.text_select'), 'id' => 'item_manual_reconciled_tax_id_4_' . $item_manual_reconciled_row]) !!}
                                                                            </td>
                                                                            <td style="padding: 0 0 3px 0;">
                                                                                {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][amount_base_4]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.amount_base_4', round($item->amount_base_4, 2)), ['class' => 'form-control input-sm text-right','id' => 'item_manual_reconciled_amount_base_4_' . $item_manual_reconciled_row, 'placeholder' => __('sales/customer_payment.column_reconciled_amount_base'), 'step' => 'any']) !!}
                                                                            </td>
                                                                        </tr>
                                                                        <tr class="col-taxes-{{ $item_manual_reconciled_row }} {{ !empty(old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_5',$item->tax_id_5)) ? '' : 'hidden' }}">
                                                                            <td style="width:50%; padding: 0 0 3px 0;">
                                                                                {!! Form::select('item_manual_reconciled[' . $item_manual_reconciled_row . '][tax_id_5]', $taxes,old('item_manual_reconciled.' . $item_manual_reconciled_row . '.tax_id_5',$item->tax_id_5), ['class' => 'form-control input-sm','placeholder' => __('general.text_select'), 'id' => 'item_manual_reconciled_tax_id_5_' . $item_manual_reconciled_row]) !!}
                                                                            </td>
                                                                            <td style="padding: 0 0 3px 0;">
                                                                                {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][amount_base_5]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.amount_base_5', round($item->amount_base_5, 2)), ['class' => 'form-control input-sm text-right','id' => 'item_manual_reconciled_amount_base_5_' . $item_manual_reconciled_row, 'placeholder' => __('sales/customer_payment.column_reconciled_amount_base'), 'step' => 'any']) !!}
                                                                            </td>
                                                                        </tr>
                                                                    </table>
                                                                    <button type="button" onclick="addTaxItemManualReconciled('{{ $item_manual_reconciled_row }}');" class="btn btn-xs btn-default" style="margin-top: 3px;"> <i class="fa fa-plus"></i></button>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.amount_total') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][amount_total]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.amount_total',round($item->amount_total,2)), ['class' => 'form-control input-sm text-right col-last-balance','id' => 'item_manual_reconciled_amount_total_' . $item_manual_reconciled_row,'required', 'step' => 'any']) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.amount_total'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.amount_total') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.number_of_payment') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][number_of_payment]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.number_of_payment',$item->number_of_payment), ['class' => 'form-control input-sm text-center col-number-of-payment','id' => 'item_manual_reconciled_number_of_payment_' . $item_manual_reconciled_row,'required', 'step' => 'any']) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.number_of_payment'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.number_of_payment') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.last_balance') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][last_balance]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.last_balance',round($item->last_balance,2)), ['class' => 'form-control input-sm text-right col-last-balance','id' => 'item_manual_reconciled_last_balance_' . $item_manual_reconciled_row,'required', 'step' => 'any']) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.last_balance'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.last_balance') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.amount_reconciled') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][amount_reconciled]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.amount_reconciled',round($item->amount_reconciled,2)), ['class' => 'form-control input-sm text-right col-amount-reconciled','id' => 'item_manual_reconciled_amount_reconciled_' . $item_manual_reconciled_row,'required', 'step' => 'any']) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.amount_reconciled'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.amount_reconciled') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.current_balance') ? ' has-error' : '' }}">
                                                                        {!! Form::number('item_manual_reconciled[' . $item_manual_reconciled_row . '][current_balance]', old('item_manual_reconciled.' . $item_manual_reconciled_row . '.current_balance',round($item->current_balance,2)), ['class' => 'form-control input-sm text-right col-current-balance','id' => 'item_manual_reconciled_current_balance_' . $item_manual_reconciled_row,'required', 'step' => 'any', 'readonly']) !!}
                                                                        @if ($errors->has('item_manual_reconciled.'.$item_manual_reconciled_row.'.current_balance'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_manual_reconciled.'.$item_manual_reconciled_row.'.current_balance') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        @endforeach
                                                        @php
                                                            $item_manual_reconciled_row++;
                                                        @endphp
                                                        <!-- /Items -->
                                                        <!-- Agregar nuevo item -->
                                                        <tr id="add_item_manual_reconciled">
                                                            <td class="text-center">
                                                                <button type="button"
                                                                        onclick="addItemManualReconciled();"
                                                                        class="btn btn-xs btn-primary"
                                                                        style="margin-bottom: 0;">
                                                                    <i class="fa fa-plus"></i>
                                                                </button>
                                                                <button type="button"
                                                                        id="add_manual_xml"
                                                                        class="btn btn-xs btn-primary ladda-button ladda-button-add-xml mt-2"
                                                                        style="margin-bottom: 0;">
                                                                    <i class="fa fa-plus"></i> {{ __('general.button_xml') }}
                                                                </button>
                                                            </td>
                                                            <td class="text-right" colspan="13"></td>
                                                        </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div role="tabpanel" class="tab-pane fade" id="tab_spei"
                                         aria-labelledby="spei-tab">
                                        <div class="row">
                                            <div class="col-md-4 col-xs-12">
                                                <div class="form-group form-group-sm">
                                                    {!! html_entity_decode(Form::label('tipo_cadena_pago', __('sales/customer_payment.entry_tipo_cadena_pago') . ' ', ['class' => 'control-label'])) !!}
                                                    {!! Form::select('tipo_cadena_pago', $tipo_cadena_pagos,old('tipo_cadena_pago',($duplicate_ci->tipo_cadena_pago ?? '')), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('certificado_pago') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('certificado_pago', __('sales/customer_payment.entry_certificado_pago') . '', ['class' => 'control-label'])) !!}
                                                    {!! Form::textarea('certificado_pago', old('certificado_pago',($duplicate_ci->certificado_pago ?? '')), ['class' => 'form-control', 'placeholder' => __('sales/customer_payment.entry_certificado_pago'),'rows' => '3']) !!}
                                                    @if ($errors->has('certificado_pago'))
                                                        <span class="help-block"><small>{{ $errors->first('certificado_pago') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('cadena_pago') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('cadena_pago', __('sales/customer_payment.entry_cadena_pago') . '', ['class' => 'control-label'])) !!}
                                                    {!! Form::textarea('cadena_pago', old('cadena_pago',($duplicate_ci->cadena_pago ?? '')), ['class' => 'form-control', 'placeholder' => __('sales/customer_payment.entry_cadena_pago'),'rows' => '3']) !!}
                                                    @if ($errors->has('cadena_pago'))
                                                        <span class="help-block"><small>{{ $errors->first('cadena_pago') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('sello_pago') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('sello_pago', __('sales/customer_payment.entry_sello_pago') . '', ['class' => 'control-label'])) !!}
                                                    {!! Form::textarea('sello_pago', old('sello_pago',($duplicate_ci->sello_pago ?? '')), ['class' => 'form-control', 'placeholder' => __('sales/customer_payment.entry_sello_pago'),'rows' => '3']) !!}
                                                    @if ($errors->has('sello_pago'))
                                                        <span class="help-block"><small>{{ $errors->first('sello_pago') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div role="tabpanel" class="tab-pane fade" id="tab_relations"
                                         aria-labelledby="relations-tab">
                                        <div class="row">
                                            <div class="col-md-4 col-xs-12">
                                                <div class="form-group form-group-sm{{ $errors->has('cfdi_relation_id') ? ' has-error' : '' }}">
                                                    {!! html_entity_decode(Form::label('cfdi_relation_id', __('sales/customer_payment.entry_cfdi_relation_id') . ' ', ['class' => 'control-label'])) !!}
                                                    {!! Form::select('cfdi_relation_id', $cfdi_relations,old('cfdi_relation_id'), ['class' => 'form-control', 'placeholder' => __('general.text_select')]) !!}
                                                    @if ($errors->has('cfdi_relation_id'))
                                                        <span class="help-block"><small>{{ $errors->first('cfdi_relation_id') }}</small></span>
                                                    @endif
                                                </div>
                                            </div>
                                            <div class="col-md-12 col-xs-12">
                                                <div class="table-responsive">
                                                    <table class="table table-condensed table-hover table-bordered table-striped"
                                                           id="items_relation">
                                                        <thead>
                                                        <tr>
                                                            <th width="5%"
                                                                class="text-center">@lang('general.column_actions')</th>
                                                            <th width="25%"
                                                                class="text-center">@lang('sales/customer_payment.column_relation_relation_id')</th>
                                                            <th width="65%"
                                                                class="text-center">@lang('sales/customer_payment.column_relation_uuid')</th>
                                                        </tr>
                                                        </thead>
                                                        <tbody>
                                                        <!-- Items -->
                                                        @php
                                                            $item_relation_row = 1;
                                                            $items_relation = old('item_relation',[]);
                                                        @endphp
                                                        @foreach ($items_relation as $item_relation_row => $item)
                                                            @php
                                                                $tmp_uuid = '';
                                                                $tmp_customer_payment_relations = [];
                                                                if(!empty(old('item_relation.' . $item_relation_row . '.relation_id'))){
                                                                    $tmp = \App\Models\Sales\CustomerPayment::find(old('item_relation.' . $item_relation_row . '.relation_id'));
                                                                    $tmp_customer_payment_relations = $tmp->get()->pluck('text_select2','id');
                                                                }
                                                            @endphp
                                                            <tr id="item_relation_row_{{ $item_relation_row }}">
                                                                <td class="text-center"
                                                                    style="vertical-align: middle;">
                                                                    <button type="button"
                                                                            onclick="$('#item_relation_row_{{ $item_relation_row }}').remove();"
                                                                            class="btn btn-xs btn-danger"
                                                                            style="margin-bottom: 0;">
                                                                        <i class="fa fa-trash"></i>
                                                                    </button>
                                                                    <!-- input hidden -->
                                                                    <input type="hidden"
                                                                           id="item_relation_id_{{ $item_relation_row }}"
                                                                           name="item_relation[{{ $item_relation_row }}][id]"
                                                                           value="{{ old('item_relation.' . $item_relation_row . '.id') }}">
                                                                    <!-- /.input hidden -->
                                                                </td>
                                                                <td class="text-center align-middle">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_relation.'.$item_relation_row.'.relation_id') ? ' has-error' : '' }}">
                                                                        {!! Form::select('item_relation[' . $item_relation_row . '][relation_id]', $tmp_customer_payment_relations,old('item_relation.' . $item_relation_row . '.relation_id'), ['class' => 'form-control input-sm col-relation-id', 'placeholder' => __('general.text_select'),'id' => 'item_relation_relation_id_' . $item_relation_row,'data-row' => $item_relation_row]) !!}
                                                                        @if ($errors->has('item_relation.'.$item_relation_row.'.relation_id'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_relation.'.$item_relation_row.'.relation_id') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                                <td class="text-center align-middle">
                                                                    <div class="form-group form-group-sm{{ $errors->has('item_relation.'.$item_relation_row.'.uuid_related') ? ' has-error' : '' }}">
                                                                        {!! Form::text('item_relation[' . $item_relation_row . '][uuid_related]',old('item_relation.' . $item_relation_row . '.uuid_related'), ['class' => 'form-control text-center input-sm col-uuid-related','required','id' => 'item_relation_uuid_related_' . $item_relation_row,'data-row' => $item_relation_row]) !!}
                                                                        @if ($errors->has('item_relation.'.$item_relation_row.'.uuid_related'))
                                                                            <span class="help-block"><small>{{ $errors->first('item_relation.'.$item_relation_row.'.uuid_related') }}</small></span>
                                                                        @endif
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        @endforeach
                                                        @php
                                                            $item_relation_row++;
                                                        @endphp
                                                        <!-- /Items -->
                                                        <!-- Agregar nuevo item -->
                                                        <tr id="add_item_relation">
                                                            <td class="text-center">
                                                                <button type="button"
                                                                        onclick="addItemCfdiRelation();"
                                                                        class="btn btn-xs btn-primary"
                                                                        style="margin-bottom: 0;">
                                                                    <i class="fa fa-plus"></i>
                                                                </button>
                                                            </td>
                                                            <td class="text-right" colspan="2"></td>
                                                        </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Footer form -->
                            <div class="ln_solid"></div>
                            <div class="row">
                                <div class="col-md-12 col-xs-12 text-right footer-form">
                                    {!! Form::button(__('general.button_pre_payment'),['type' => 'submit', 'class' => 'btn btn-sm btn-info ladda-button','name' => 'pre_payment', 'value' => '1']) !!}
                                    &nbsp;&nbsp;
                                    {!! Form::button(__('general.button_stamp'),['type' => 'submit', 'class' => 'btn btn-sm btn-primary ladda-button']) !!}
                                    &nbsp;&nbsp;
                                    <a href="{{route('customer-payments.index',request()->except('page'))}}"
                                       class="btn btn-sm btn-default">@lang('general.button_discard')</a>
                                </div>
                            </div>
                            <!-- /Footer form -->
                            {!! Form::close() !!}
                        </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">
        var item_reconciled_row = "{{ $item_reconciled_row }}";
        var item_manual_reconciled_row = "{{ $item_manual_reconciled_row }}";
        var item_relation_row = "{{ $item_relation_row }}";

        function totalItemReconciled() {
            $.ajax({
                url: "{{ route('customer-payments/total-reconciled-lines') }}",
                type: "POST",
                dataType: "JSON",
                data: $("#form").serialize(),
                success: function (data) {
                    if (data) {
                        $.each(data.items_reconciled, function (key, value) {
                            $("#form #item_reconciled_txt_balance_" + key).html(value);
                        });
                        $("#form #reconciled_txt_amount").html(data.amount);
                        $("#form #reconciled_txt_amount_reconciled").html(data.amount_reconciled);
                        $("#form #reconciled_txt_amount_per_reconciled").html(data.amount_per_reconciled);
                    }
                },
                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);
                    }
                }
            });
        }

        function addItemManualReconciled() {
            var html = '';

            html += '<tr id="item_manual_reconciled_row_' + item_manual_reconciled_row + '">';
            html += '<td class="text-center" style="vertical-align: middle;">';
            html += '<button type="button" onclick="$(\'#item_manual_reconciled_row_' + item_manual_reconciled_row + '\').remove();" class="btn btn-xs btn-danger" style="margin-bottom: 0;">';
            html += '<i class="fa fa-trash"></i>';
            html += '</button>';
            html += '<input type="hidden" name="item_manual_reconciled[' + item_manual_reconciled_row + '][id]" id="item_manual_reconciled_id_' + item_manual_reconciled_row + '" /> ';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="text" class="form-control input-sm text-center col-manual-uuid-related" name="item_manual_reconciled[' + item_manual_reconciled_row + '][uuid_related]" id="item_manual_reconciled_uuid_related_' + item_manual_reconciled_row + '" required data-row="' + item_manual_reconciled_row + '"/>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="text" class="form-control input-sm text-center col-serie-related" name="item_manual_reconciled[' + item_manual_reconciled_row + '][serie_related]" id="item_manual_reconciled_serie_related_' + item_manual_reconciled_row + '" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="text" class="form-control input-sm text-center col-folio-related" name="item_manual_reconciled[' + item_manual_reconciled_row + '][folio_related]" id="item_manual_reconciled_folio_related_' + item_manual_reconciled_row + '" />';
            html += '</div>';
            html += '</td>';
            html += '<td class="text-center">';
            html += '<div class="form-group form-group-sm">';
            html += '<select class="form-control input-sm col-currency-code-related" name="item_manual_reconciled[' + item_manual_reconciled_row + '][currency_code_related]" id="item_manual_reconciled_currency_code_related_' + item_manual_reconciled_row + '" required>';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            @foreach($currency_codes as $key => $value)
                html += '<option value="{{ $key }}">{{ $value }}</option>';
            @endforeach
                html += '</select>';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-center col-currency-value" name="item_manual_reconciled[' + item_manual_reconciled_row + '][currency_value]" id="item_manual_reconciled_currency_value_' + item_manual_reconciled_row + '" step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td class="text-center">';
            html += '<div class="form-group form-group-sm">';
            html += '<select class="form-control input-sm col-payment-method-code-related" name="item_manual_reconciled[' + item_manual_reconciled_row + '][payment_method_code_related]" id="item_manual_reconciled_payment_method_code_related_' + item_manual_reconciled_row + '" required>';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            @foreach($payment_method_codes as $key => $value)
                html += '<option value="{{ $key }}">{{ $value }}</option>';
            @endforeach
                html += '</select>';
            html += '</div>';
            html += '</td>';
            html += '<td>';

                html += '<table>';
                html += '<tr class="col-taxes-' + item_manual_reconciled_row + '">';
                html += '<td style="width:50%; padding: 0 0 3px 0;">';
                html += '<select class="form-control input-sm" name="item_manual_reconciled[' + item_manual_reconciled_row + '][tax_id_1]" id="item_manual_reconciled_tax_id_1_' + item_manual_reconciled_row + '">';
                    html += '<option value="">' + "@lang('general.text_select')" + '</option>';
                @foreach($taxes as $key => $value)
                    html += '<option value="{{ $key }}">{{ $value }}</option>';
                @endforeach
                html += '</select>';
                html += '</td>';
                html += '<td style="padding: 0 0 3px 0;">';
                html += ' <input type="number" class="form-control input-sm text-right" name="item_manual_reconciled[' + item_manual_reconciled_row + '][amount_base_1]" id="item_manual_reconciled_amount_base_1_' + item_manual_reconciled_row + '" placeholder="' + "@lang('sales/customer_payment.column_reconciled_amount_base')" + '" step="any"/>';
                html += '</td>';
                html += '</tr>';
                html += '<tr class="col-taxes-' + item_manual_reconciled_row + ' hidden">';
                html += '<td style="width:50%; padding: 0 0 3px 0;">';
                html += '<select class="form-control input-sm" name="item_manual_reconciled[' + item_manual_reconciled_row + '][tax_id_2]" id="item_manual_reconciled_tax_id_2_' + item_manual_reconciled_row + '">';
                    html += '<option value="">' + "@lang('general.text_select')" + '</option>';
                @foreach($taxes as $key => $value)
                    html += '<option value="{{ $key }}">{{ $value }}</option>';
                @endforeach
                html += '</select>';
                html += '</td>';
                html += '<td style="padding: 0 0 3px 0;">';
                html += ' <input type="number" class="form-control input-sm text-right" name="item_manual_reconciled[' + item_manual_reconciled_row + '][amount_base_2]" id="item_manual_reconciled_amount_base_2_' + item_manual_reconciled_row + '" placeholder="' + "@lang('sales/customer_payment.column_reconciled_amount_base')" + '" step="any"/>';
                html += '</td>';
                html += '</tr>';
                html += '<tr class="col-taxes-' + item_manual_reconciled_row + ' hidden">';
                html += '<td style="width:50%; padding: 0 0 3px 0;">';
                html += '<select class="form-control input-sm" name="item_manual_reconciled[' + item_manual_reconciled_row + '][tax_id_3]" id="item_manual_reconciled_tax_id_3_' + item_manual_reconciled_row + '">';
                    html += '<option value="">' + "@lang('general.text_select')" + '</option>';
                @foreach($taxes as $key => $value)
                    html += '<option value="{{ $key }}">{{ $value }}</option>';
                @endforeach
                html += '</select>';
                html += '</td>';
                html += '<td style="padding: 0 0 3px 0;">';
                html += ' <input type="number" class="form-control input-sm text-right" name="item_manual_reconciled[' + item_manual_reconciled_row + '][amount_base_3]" id="item_manual_reconciled_amount_base_3_' + item_manual_reconciled_row + '" placeholder="' + "@lang('sales/customer_payment.column_reconciled_amount_base')" + '" step="any"/>';
                html += '</td>';
                html += '</tr>';
                html += '<tr class="col-taxes-' + item_manual_reconciled_row + ' hidden">';
                html += '<td style="width:50%; padding: 0 0 3px 0;">';
                html += '<select class="form-control input-sm" name="item_manual_reconciled[' + item_manual_reconciled_row + '][tax_id_4]" id="item_manual_reconciled_tax_id_4_' + item_manual_reconciled_row + '">';
                    html += '<option value="">' + "@lang('general.text_select')" + '</option>';
                @foreach($taxes as $key => $value)
                    html += '<option value="{{ $key }}">{{ $value }}</option>';
                @endforeach
                html += '</select>';
                html += '</td>';
                html += '<td style="padding: 0 0 3px 0;">';
                html += ' <input type="number" class="form-control input-sm text-right" name="item_manual_reconciled[' + item_manual_reconciled_row + '][amount_base_4]" id="item_manual_reconciled_amount_base_4_' + item_manual_reconciled_row + '" placeholder="' + "@lang('sales/customer_payment.column_reconciled_amount_base')" + '" step="any"/>';
                html += '</td>';
                html += '</tr>';
                html += '<tr class="col-taxes-' + item_manual_reconciled_row + ' hidden">';
                html += '<td style="width:50%; padding: 0 0 3px 0;">';
                html += '<select class="form-control input-sm" name="item_manual_reconciled[' + item_manual_reconciled_row + '][tax_id_5]" id="item_manual_reconciled_tax_id_5_' + item_manual_reconciled_row + '">';
                    html += '<option value="">' + "@lang('general.text_select')" + '</option>';
                @foreach($taxes as $key => $value)
                    html += '<option value="{{ $key }}">{{ $value }}</option>';
                @endforeach
                html += '</select>';
                html += '</td>';
                html += '<td style="padding: 0 0 3px 0;">';
                html += ' <input type="number" class="form-control input-sm text-right" name="item_manual_reconciled[' + item_manual_reconciled_row + '][amount_base_5]" id="item_manual_reconciled_amount_base_5_' + item_manual_reconciled_row + '" placeholder="' + "@lang('sales/customer_payment.column_reconciled_amount_base')" + '" step="any"/>';
                html += '</td>';
                html += '</tr>';
                html += '</table>';
                html += '<button type="button" onclick="addTaxItemManualReconciled(' + item_manual_reconciled_row + ');" class="btn btn-xs btn-default" style="margin-top: 3px;"> <i class="fa fa-plus"></i></button>';

            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-right col-amount-total" name="item_manual_reconciled[' + item_manual_reconciled_row + '][amount_total]" id="item_manual_reconciled_amount_total_' + item_manual_reconciled_row + '" required step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-center col-number-of-payment" name="item_manual_reconciled[' + item_manual_reconciled_row + '][number_of_payment]" id="item_manual_reconciled_number_of_payment_' + item_manual_reconciled_row + '" required step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-right col-last-balance" name="item_manual_reconciled[' + item_manual_reconciled_row + '][last_balance]" id="item_manual_reconciled_last_balance_' + item_manual_reconciled_row + '" required step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-right col-amount-reconciled" name="item_manual_reconciled[' + item_manual_reconciled_row + '][amount_reconciled]" id="item_manual_reconciled_amount_reconciled_' + item_manual_reconciled_row + '" required step="any" />';
            html += '</div>';
            html += '</td>';
            html += '<td>';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="number" class="form-control input-sm text-right col-current-balance" name="item_manual_reconciled[' + item_manual_reconciled_row + '][current_balance]" id="item_manual_reconciled_current_balance_' + item_manual_reconciled_row + '" required step="any" readonly="readonly" />';
            html += '</div>';
            html += '</td>';
            html += '</tr>';

            $("#form #items_manual_reconciled tbody #add_item_manual_reconciled").before(html);


            item_manual_reconciled_row++;
        }

        function addTaxItemManualReconciled(row)
        {
            var taxes = $("#form").find('.col-taxes-' + row + '');
            taxes.each(function( index ) {
                if($(this).hasClass('hidden')){
                    $(this).removeClass('hidden')
                    return false
                }
            });
        }

        function addItemCfdiRelation() {
            var html = '';

            html += '<tr id="item_relation_row_' + item_relation_row + '">';
            html += '<td class="text-center" style="vertical-align: middle;">';
            html += '<button type="button" onclick="$(\'#item_relation_row_' + item_relation_row + '\').remove();" class="btn btn-xs btn-danger" style="margin-bottom: 0;">';
            html += '<i class="fa fa-trash"></i>';
            html += '</button>';
            html += '<input type="hidden" name="item_relation[' + item_relation_row + '][id]" id="item_relation_id_' + item_relation_row + '" /> ';
            html += '</td>';
            html += '<td class="text-center align-middle">';
            html += '<div class="form-group form-group-sm">';
            html += '<select class="form-control input-sm col-relation-id" name="item_relation[' + item_relation_row + '][relation_id]" id="item_relation_relation_id_' + item_relation_row + '" data-row="' + item_relation_row + '" >';
            html += '<option selected="selected" value="">@lang('general.text_select')</option>';
            html += '</select>';
            html += '</div>';
            html += '</td>';
            html += '<td class="text-center align-middle">';
            html += '<div class="form-group form-group-sm">';
            html += '<input type="text" class="form-control input-sm text-center col-uuid-related" name="item_relation[' + item_relation_row + '][uuid_related]" id="item_relation_uuid_related_' + item_relation_row + '" required />';
            html += '</div>';
            html += '</td>';
            html += '</tr>';

            $("#form #items_relation tbody #add_item_relation").before(html);

            /* Configura select2 */
            initItemCfdiRelation();

            item_relation_row++;
        }


        function initItemCfdiRelation() {
            /*Busqueda de facturas*/
            $("#form #items_relation tbody .col-relation-id").select2({
                ajax: {
                    url: "{{route('customer-payments/autocomplete-cfdi')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                            customer_id: $("#form select[name='customer_id']").val(),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                width: "auto",
                dropdownAutoWidth: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 2
            });
        }

        //Obtener cuentas bancarias
        function getCustomerBankAccount(id){
            if (id) {
                let customer_bank_account_id = $("#form select[name='customer_bank_account_id']");
                let tmp = customer_bank_account_id.val();
                customer_bank_account_id.html("");
                $.ajax({
                    url: "{{ route('customers/get-customer-bank-accounts') }}",
                    type: "GET",
                    dataType: "JSON",
                    data: "id=" + id + "&customer_bank_account_id=" + tmp + "",
                    success: function (data) {
                        if (data.html) {
                            customer_bank_account_id.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);
                        }
                    }
                });
            }
        }

        function getCustomerInvoiceBalances(){
            let customer_id = $("#form select[name='customer_id']").val();
            let currency_id = $("#form select[name='currency_id']").val();
            let currency_value = $("#form input[name='currency_value']").val();
            let filter_currency_id = 0; //Filtra solo facturas de la misma moneda
            $("#form #items_reconciled tbody").html("");
            if(customer_id && currency_id){
                $.ajax({
                    url: "{{ route('customer-invoices/balances') }}",
                    type: "GET",
                    dataType: "JSON",
                    data: "customer_id=" + customer_id + "&currency_id=" + currency_id + "&currency_value=" + currency_value + "&filter_currency_id=" + filter_currency_id + "",
                    success: function (data) {
                        if (data.html) {
                            $("#form #items_reconciled 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);
                        }
                    }
                });
            }
        }

        function totalItemManualReconciled() {
            $.ajax({
                url: "{{ route('customer-payments/total-item-manual-reconciled') }}",
                type: "POST",
                dataType: "JSON",
                data: $("#form").serialize(),
                success: function (data) {
                    if (data) {
                        $.each(data.items_manual_reconciled, function (key, value) {
                            $("#item_manual_reconciled_current_balance_" + key).val(value);
                        });
                    }
                },
                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);
                    }
                }
            });
        }

        $(function () {
            /*Configura datepicker*/
            moment.locale("{{ substr(app()->getLocale(),0,2) }}");
            $("#form input[name='date']").daterangepicker({
                singleDatePicker: true,
                timePicker: true,
                timePicker24Hour: true,
                showDropdowns: true,
                locale: {
                    format: "{{ setting('datetime_picker_format','DD-MM-YYYY HH:mm:ss') }}"
                },
                autoUpdateInput: false
            }, function (chosen_date) {
                $("#form input[name='date']").val(chosen_date.format("{{ setting('datetime_picker_format','DD-MM-YYYY HH:mm:ss') }}"));
            });
            $("#form input[name='date_payment']").daterangepicker({
                singleDatePicker: true,
                timePicker: true,
                timePicker24Hour: true,
                showDropdowns: true,
                locale: {
                    format: "{{ setting('datetime_picker_format','DD-MM-YYYY HH:mm:ss') }}"
                },
                autoUpdateInput: false,
            }, function (chosen_date) {
                $("#form input[name='date_payment']").val(chosen_date.format("{{ setting('datetime_picker_format','DD-MM-YYYY HH:mm:ss') }}"));
            });

            $("#form input[name='cfdi']").on("change", function () {
                if($(this).is(':checked')){
                    $("#form #btn_stamp").text("{{__('general.button_stamp')}}");
                }else{
                    $("#form #btn_stamp").text("{{__('general.button_save')}}");
                }
            });

            /* Configura select2 para buscar cliente*/
            $("#form select[name='customer_id']").select2({
                ajax: {
                    url: "{{route('customers/autocomplete')}}",
                    dataType: "JSON",
                    delay: 250,
                    data: function (params) {
                        return {
                            term: $.trim(params.term),
                        };
                    },
                    processResults: function (data, page) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                placeholder: "@lang('general.text_select')",
                theme: "bootstrap",
                width: "100%",
                dropdownAutoWidth: true,
                allowClear: true,
                language: "{{ str_replace('_', '-', app()->getLocale()) }}",
                minimumInputLength: 3
            }).on("change", function () { //Selecciona cliente
                let id = $(this).val();
                if (id) {
                    $.ajax({
                        url: "{{ route('customers/get-customer') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form select[name='payment_way_id']").val(data.payment_way_id);
                            $("#form select[name='tax_regimen_customer_id']").val(data.tax_regimen_id);

                            //Obtener cuentas bancarias
                            getCustomerBankAccount(id);

                            //Obtener facturas con saldos
                            getCustomerInvoiceBalances();
                        },
                        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);
                            }
                        }
                    });
                }
            });
            /* Selecciona sucursal */
            $("#form select[name='branch_office_id']").on("change", function () {
                let id = $(this).val();
                if (id) {
                    $.ajax({
                        url: "{{ route('branch-offices/get-branch-office') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form input[name='date']").val(data.cfdi_date_time);
                            totalItemReconciled();
                        },
                        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("change");
            /* Selecciona moneda */
            $("#form select[name='currency_id']").on("change", function () {
                let id = $(this).val();
                if (id) {
                    $.ajax({
                        url: "{{ route('currencies/get-currency') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form input[name='currency_value']").val(data.rate);
                            $("#form #info_reconciled_balance_currency").text("(" + data.code + ")");

                            //Obtener facturas con saldos
                            getCustomerInvoiceBalances();

                            totalItemReconciled();
                        },
                        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);
                            }
                        }
                    });
                }
            });

            @if($errors->isEmpty() && empty(session('flash_notification', collect())->toArray()))
            $("#form select[name='currency_id']").trigger("change");
            @endif

            /*Modal para buscar clientes*/
            $(".btn-customer-search").on("click", function (e) {
                e.preventDefault();
                $.ajax({
                    url: "{{route('customers/modal-search')}}",
                    type: "GET",
                    dataType: "JSON",
                    data: "active_btn_select=1",
                    success: function (data) {
                        $("#modals").html(data.html);
                        $("#modal_customer_search").modal("show");
                    },
                    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);
                        }
                    }
                });
            });
            /*Seleccionar cliente*/
            $(document).on("click", '#form_modal_customer_search #customers .btn-select-customer', function (e) {
                e.preventDefault();
                let option = new Option($(this).attr('data-name'), $(this).attr('data-id'), false, true);
                $("#form select[name='customer_id']").append(option).trigger('change');
                $("#modal_customer_search").modal("hide");
            });

            /* Actualiza facturas para el tipo de cambio */
            $("#form select[name='currency_value']").on("change", function () {
                //Obtener facturas con saldos
                getCustomerInvoiceBalances();
            });

            $("#form input[name='amount']").on("change", function () {
                totalItemReconciled();
            });

            /* init de Funciones */
            initItemCfdiRelation();
            totalItemReconciled();

            /* Eventos en items_reconciled */
            $(document).on("keyup", "#form #items_reconciled tbody .col-amount-reconciled,#form #items_reconciled tbody .col-currency-value", function () {
                totalItemReconciled();
            });

            /* Eventos en items cfdi relation */
            /*Selecciona factura*/
            $(document).on('select2:select', '#form #items_relation tbody .col-relation-id', function (e) {
                let id = $(this).val();
                let row = $(this).attr('data-row');
                if (id) {
                    $.ajax({
                        url: "{{ route('customer-payments/get-customer-payment') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "id=" + id,
                        success: function (data) {
                            $("#form #item_relation_uuid_related_" + row).val(data.uuid);
                        },
                        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);
                            }
                        }
                    });
                }
            });

            /* Eventos en items_manual_reconciled */
            $(document).on("keyup", "#form #items_manual_reconciled tbody .col-last-balance, #form #items_manual_reconciled tbody .col-amount-reconciled", function () {
                totalItemManualReconciled();
            });

            $("#form #add_manual_xml").on("click", function (e) {
                $("#form input[name='file_add_xml']").click()
            })

            var ladda_button_import = Ladda.create(document.querySelector('.ladda-button-add-xml'));
            $("#form input[name='file_add_xml']").on("change", function (e) {
                var formData = new FormData();
                formData.append('file_add_xml', $(this)[0].files[0]);
                ladda_button_import.start();
                $.ajax({
                    url: "{{ route('customer-payments/add-manual-xml') }}",
                    type: "POST",
                    dataType: "JSON",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if(data.data){
                            addItemManualReconciled()
                            let dataTmp = data.data
                            let rowTmp = (item_manual_reconciled_row - 1)
                            $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[uuid_related\]']").val(dataTmp.uuid)
                            $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[serie_related\]']").val(dataTmp.serie)
                            $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[folio_related\]']").val(dataTmp.folio)
                            $("#form select[name='item_manual_reconciled\[" + rowTmp + "\]\[currency_code_related\]']").val(dataTmp.currency_code)
                            $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[currency_value\]']").val(dataTmp.currency_value)
                            $("#form select[name='item_manual_reconciled\[" + rowTmp + "\]\[payment_method_code_related\]']").val(dataTmp.payment_method_code)
                            $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[amount_total\]']").val(dataTmp.amount_total)
                            $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[number_of_payment\]']").val(1)
                            $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[last_balance\]']").val(dataTmp.amount_total).tri
                            $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[amount_reconciled\]']").val(dataTmp.amount_total)
                            $.each( dataTmp.taxes, function( key, element ) {
                                let keyTmp = key + 1
                                $("#form select[name='item_manual_reconciled\[" + rowTmp + "\]\[tax_id_" + keyTmp + "\]']").val(element.id)
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[amount_base_" + keyTmp + "\]']").val(element.amount_base)
                                $("#form select[name='item_manual_reconciled\[" + rowTmp + "\]\[tax_id_" + keyTmp + "\]']").parent().parent().removeClass('hidden')
                            });


                            totalItemManualReconciled();
                        }
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            let message = error.responseJSON.error;
                            let msg_error = message
                            if(typeof(message) === "object"){
                                $.each( message, function( key, value ) {
                                    msg_error = value
                                });
                            }
                            $("#general_messages").html(alertMessage("danger", msg_error));
                            setTimeout(function () {
                                $("#general_messages").html("");
                            }, 5000);
                        } else if (error.status == 403 || error.status == 401) {
                            location.href = "{{ route('login') }}";
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    },
                    complete: function(data) {
                        Ladda.stopAll();
                    }
                });
            })
            $(document).on("change", "#form .col-manual-uuid-related", function () {
                let uuid = $(this).val();
                let row = $(this).attr('data-row');
                if(row && !$("#form input[name='item_manual_reconciled\[" + row + "\]\[amount_total\]']").val()){
                    $.ajax({
                        url: "{{ route('customer-payments/add-manual-uuid') }}",
                        type: "GET",
                        dataType: "JSON",
                        data: "uuid=" + uuid,
                        success: function (data) {
                            if(data.data && data.data.uuid){

                                let dataTmp = data.data
                                let rowTmp = row
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[uuid_related\]']").val(dataTmp.uuid)
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[serie_related\]']").val(dataTmp.serie)
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[folio_related\]']").val(dataTmp.folio)
                                $("#form select[name='item_manual_reconciled\[" + rowTmp + "\]\[currency_code_related\]']").val(dataTmp.currency_code)
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[currency_value\]']").val(dataTmp.currency_value)
                                $("#form select[name='item_manual_reconciled\[" + rowTmp + "\]\[payment_method_code_related\]']").val(dataTmp.payment_method_code)
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[amount_total\]']").val(dataTmp.amount_total)
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[number_of_payment\]']").val(1)
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[last_balance\]']").val(dataTmp.amount_total).tri
                                $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[amount_reconciled\]']").val(dataTmp.amount_total)
                                $.each( dataTmp.taxes, function( key, element ) {
                                    let keyTmp = key + 1
                                    $("#form select[name='item_manual_reconciled\[" + rowTmp + "\]\[tax_id_" + keyTmp + "\]']").val(element.id)
                                    $("#form input[name='item_manual_reconciled\[" + rowTmp + "\]\[amount_base_" + keyTmp + "\]']").val(element.amount_base)
                                    $("#form select[name='item_manual_reconciled\[" + rowTmp + "\]\[tax_id_" + keyTmp + "\]']").parent().parent().removeClass('hidden')
                                });


                                totalItemManualReconciled();
                            }
                        },
                        error: function (error, textStatus, errorThrown) {
                            if (error.status == 422) {
                                let message = error.responseJSON.error;
                                let msg_error = message
                                if(typeof(message) === "object"){
                                    $.each( message, function( key, value ) {
                                        msg_error = value
                                    });
                                }
                                $("#general_messages").html(alertMessage("danger", msg_error));
                                setTimeout(function () {
                                    $("#general_messages").html("");
                                }, 5000);
                            } else if (error.status == 403 || error.status == 401) {
                                location.href = "{{ route('login') }}";
                            } else {
                                alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                            }
                        },
                        complete: function(data) {
                        }
                    });
                }
            })

        });

    </script>
@endsection
