<?php (defined('BASEPATH')) or exit('No direct script access allowed'); ?>
<link rel="stylesheet" href="<?= $assets ?>dist/css/pages/sales.css">
<link rel="stylesheet" href="<?= $assets ?>dist/css/pages/customers.css">

<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <?php echo form_open_multipart("sales/add", 'class="validation newsale"'); ?>
            <!-- PRIMERA SECCION: FILTROS -->
            <div class="box" style="border-top: 2.5px solid #9fc10b;">
                <div class="box-body">
                    <div class="col-lg-12">
                        <div class="alert alert-warning alert-dismissable" style="display: none" id="warning">
                            <button id="close" aria-hidden="true" class="close" type="button">×</button>
                            <center>
                                <strong style="color:red;"><i class="icon fa fa-warning"></i> <?= lang('warning'); ?></strong></br>
                                <span style="color:#484848;" id="warning_text"></span>
                            </center>
                        </div>
                        <div class="row">
                            <div class="col-md-2">
                                <div class="form-group">
                                    <?= lang("document_type", "document_type"); ?>
                                    <?php

                                    $document_list = array();
                                    $document_list[''] = "Seleccionar";
                                    foreach ($documents as $document) {
                                        $document_list[$document['id']] = $document['description'];
                                    }
                                    ?>
                                    <?= form_dropdown('document_type', $document_list, set_value('document_type', 0), 'class="form-control select2 document_type" id="document_type"  required="required" style="width:100%;"'); ?>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="form-group" style="width: 100%;">
                                        <?= lang('customer', 'customer'); ?>
                                        <div class="input-group" style="width: 100%;">
                                            <div class="search-container" style="width: 100%;">
                                                <!-- <input type="text" class="form-control" id="customer" placeholder="Buscar cliente" required="required"> -->
                                                <?= form_input('customer_name', '', 'class="form-control" id="customer" required="required" placeholder="Buscar cliente"'); ?>
                                            </div>
                                            <ul id="lista"></ul>
                                            <div class="input-group-btn">
                                                <button type="button" id="openFormButton" class="form-control btn btn-default" data-toggle="modal" data-target="#customerModal" title="<?=lang('add_customer')?>"><img src="<?=$assets?>images/agregar-usuario.png" alt="" srcset=""></button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" id="customer_id" name="customer_id" value="">
                            <input type="hidden" id="customer_name" name="customer_name" value="">
                            <input type="hidden" id="customer_is_retainer" name="customer_is_retainer" value="">
                            <input type="hidden" id="customer_retainer_percentage" name="customer_retainer_percentage" value="">
                            <input type="hidden" id="customer_type" name="customer_type" value="">
                            <style>
                                #lista{
                                    list-style: none;
                                    padding: 0;
                                    width: 100%;
                                    border: 1px solid #ccc;
                                    position: absolute; 
                                    z-index: 1000;  
                                    top: 100%;
                                    left: 0;
                                    /* display: none; */
                                    background: #fff;
                                    display: block;
                                }
                                #lista li{
                                    padding: 5px 8px;
                                    cursor: pointer;
                                }
                                #lista li:hover{
                                    background: #3c8dbc;
                                    color: #fff;
                                }
                            </style>
                            <!-- <div class="col-md-6">
                                <div class="row">
                                    <div class="form-group" style="width: 100%;">
                                        <?= lang('customer', 'customer'); ?>
                                        <div class="input-group" style="width: 100%;">
                                            comentado->   <div class="search-container">
                                                <input type="text" class="form-control" id="customerSearch" placeholder="Buscar cliente">
                                            </div>   comentado->
                                            <select name="customer" id="prueba-cus" class="form-control tip select2" required="required" style="width: 100%;">
                                                <?php foreach ($ct as $key => $value): ?>
                                                    <option value="<?= $key; ?>"><?= explode('||', $value)[0]; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                            <div class="input-group-btn">
                                                <button type="button" id="openFormButton" class="form-control btn btn-default" data-toggle="modal" data-target="#customerModal" title="<?=lang('add_customer')?>"><img src="<?=$assets?>images/agregar-usuario.png" alt="" srcset=""></button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div> -->

                            <!-- boton cliente -->
                            <!-- fin boton cliente -->
                            <?php $tomorrow = date('Y-m-d', strtotime("+1 day")); ?>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <?= lang('issue_date_2', 'issue_date_2'); ?>
                                    <?= form_input('date', set_value('date', date('Y-m-d')), 'class="form-control datetimepicker tip" id="date"  required="required"'); ?>
                                    <!-- H:i -->
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <?= lang('currency_name', 'currency_name'); ?>
                                    <?php
                                    $cy['PEN'] = lang('currency_pen');
                                    $cy['USD'] = lang('currency_usd');
                                    ?>
                                    <?= form_dropdown('currency_code', $cy, set_value('currency_code', $Settings->currency_prefix), 'class="form-control select2" id="currency_code"  required="required"'); ?>
                                </div>
                            </div>
                        </div>

                        <?php if ($this->session->userdata('traders')) { ?>
                            <div class="row">
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <?= lang("traders", "traders"); ?>
                                        <?php
                                        $trader_list = array();
                                        $trader_list[0] = "Seleccionar";
                                        foreach ($traders as $trader) {
                                            $trader_list[$trader['id']] = $trader['last_name_1'] . ' ' . $trader['last_name_2'] . ', ' . $trader['name'];
                                        }
                                        ?>
                                        <?= form_dropdown('traders_id', $trader_list, set_value('traders_id', 0), 'class="form-control select2" id="traders_id"  required="required" style="width:100%;"'); ?>
                                    </div>
                                </div>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>

            <!-- SEGUNDA SECCION: OPERACIONES -->
            <div class="box" style="border-top: 0px solid;">
                <div class="box-body">
                    <div style="padding-left:10px; padding-right:10px" class="form-group">
                        <input type="text" placeholder="<?= lang('search_product_by_name_code'); ?>" id="add_item" class="form-control">
                    </div>

                    <div style="padding-left:10px; padding-right:10px" class="row">
                        <div class="col-md-12">
                            <div class="table-responsive">
                                <table id="poTable" class="table table-striped table-bordered">
                                    <thead>
                                        <tr class="active">
                                            <th><?= lang('product'); ?></th>
                                            <!--**************TRJ044 - ALEXANDER ROCA - 23/05/2019******************-->
                                            <?php if ($advance_sale == 0) { ?>

                                                <!--**************TRJ038 - ALEXANDER ROCA - 17/04/2019******************-->
                                                <th class="col-xs-3">
                                                    <div style="margin-left:20px;"><?= lang('tax'); ?></div>
                                                </th>
                                                <!--**************TRJ038 - ALEXANDER ROCA - 17/04/2019******************-->
                                                <?php if ($plastic_bags > 0) { ?>

                                                    <th class="col-xs-1"><?= lang('quantity'); ?></th>
                                                    <th class="col-xs-1"><?= lang('price'); ?></th>
                                                    <th class="col-xs-1"><?= lang('tax_ICBPER'); ?></th>

                                                <?php } else { ?>

                                                    <th class="col-xs-2"><?= lang('quantity'); ?></th>
                                                    <th class="col-xs-2"><?= lang('price'); ?></th>

                                                <?php } ?>
                                                <th class="col-xs-1"><?= lang('importe'); ?></th>

                                            <?php } else { ?>

                                                <th class="col-xs-1"><?= lang('quantity'); ?></th>
                                                <th class="col-xs-1"><?= lang('affected'); ?></th>
                                                <th class="col-xs-1"><?= lang('exonerated'); ?></th>
                                                <th class="col-xs-1"><?= lang('exo'); ?></th>
                                                <?php if ($plastic_bags > 0) { ?>
                                                    <th class="col-xs-1"><?= lang('tax_ICBPER'); ?></th>
                                                <?php } ?>
                                                <th class="col-xs-1"><span class="text-right"><?= lang('importe'); ?></span></th>

                                            <?php } ?>
                                            <!--**************TRJ044 - ALEXANDER ROCA - 23/05/2019******************-->

                                            <th style="width:25px;"><i class="fa fa-trash-o"></i></th>
                                        </tr>
                                    </thead>
                                    <tbody id="tbody-items">
                                        <tr>
                                            <?php if ($advance_sale == 0) { ?>

                                                <?php if ($plastic_bags > 0) { ?>
                                                    <td colspan="7"><?= lang('add_product_by_searching_above_field'); ?></td>
                                                <?php } else { ?>
                                                    <td colspan="6"><?= lang('add_product_by_searching_above_field'); ?></td>
                                                <?php } ?>

                                            <?php } else { ?>

                                                <?php if ($plastic_bags > 0) { ?>
                                                    <td colspan="8"><?= lang('add_product_by_searching_above_field'); ?></td>
                                                <?php } else { ?>
                                                    <td colspan="7"><?= lang('add_product_by_searching_above_field'); ?></td>
                                                <?php } ?>

                                            <?php } ?>
                                        </tr>
                                    </tbody>
                                    <tfoot>
                                        <tr class="active">
                                            <th><?= lang('total_items'); ?>
                                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                &nbsp;&nbsp;
                                                <span id="tart">0 (0.00)</span>
                                            </th>
                                            <?php if ($plastic_bags > 0) { ?>

                                                <th class="col-xs-1"></th>
                                                <th class="col-xs-1"></th>

                                            <?php } else { ?>

                                                <th class="col-xs-2"></th>
                                                <th class="col-xs-2"></th>

                                            <?php } ?>
                                            <th class="text-right"><?= lang('subtotal'); ?></th>
                                            <!--**************TRJ044 - ALEXANDER ROCA - 24/05/2019******************-->
                                            <?php if ($advance_sale == 1) { ?>
                                                <th class="col-xs-1"></th>
                                            <?php } ?>
                                            <!--**************TRJ044 - ALEXANDER ROCA - 24/05/2019******************-->
                                            <?php if ($plastic_bags > 0) { ?>
                                                <th style="width:25px;"></th>
                                            <?php } ?>
                                            <th class="col-xs-2 text-right"><span id="gtotal">0.00</span></th>
                                            <input type="hidden" id="total_pay" value="0.00" name="total_pay">
                                            <th style="width:25px;"></th>

                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div class="text-right" style="padding-left:10px; padding-right:10px;">
                        <table class="table table-condensed">
                            <tbody>
                                <tr style="border: 1px;">
                                    <td rowspan="10">

                                    </td>
                                </tr>
                                <tr>
                                    <td style="border: none;"><?= strtoupper(lang('discount') . ':'); ?></td>
                                    <td style="col-md-2; border: none; padding-left:8%; padding-right:25px;" colspan="2"><input class="form-control input-sm kb-pad text-right" name="gdiscount" type="text" value="0.00" id="gdiscount" onClick="this.select();"></td>
                                </tr>
                                <tr>
                                    <td style="border: none;"><strong><?= strtoupper(lang('total') . ':'); ?></strong></td>
                                    <td style="border: none; padding-right:35px;" class="col-xs-2"><strong><span id="gtot">0.00</span></strong></td>
                                </tr>
                                <tr>
                                    <td style="border: none;"><?= strtoupper(lang('opgrav') . ':'); ?></td>
                                    <td style="border: none; padding-right:35px;" class="col-xs-2"><span id="gaffected">0.00</span></td>
                                    <!-- <input type="hidden" id="opgra" value="0.00" name="opgra"> -->
                                </tr>
                                <!--**********************TRJ008 - ALEXANDER ROCA - 11/04/2019******************-->
                                <tr>
                                    <td style="border: none;"><?= strtoupper(lang('opexonReal') . ':'); ?></td>
                                    <td style="border: none; padding-right:35px;" class="col-xs-2"><span id="gexoneratedReal">0.00</span></td>
                                    <!-- <input type="hidden" id="opexo" value="0.00" name="opexo"> -->
                                </tr>
                                <!--**********************TRJ008 - ALEXANDER ROCA - 11/04/2019******************-->
                                <tr>
                                    <td style="border: none;"><?= strtoupper(lang('opexon') . ':'); ?></td>
                                    <td style="border: none; padding-right:35px;" class="col-xs-2"><span id="gexonerated">0.00</span></td>
                                    <!-- <input type="hidden" id="opexo" value="0.00" name="opexo"> -->
                                </tr>
                                <?php if ($this->session->userdata('gratuito')) { ?>

                                    <tr>
                                        <td style="border: none;"><?= strtoupper(lang('opfree') . ':'); ?></td>
                                        <td style="border: none; padding-right:35px;" class="col-xs-2"><span id="ggratuita">0.00</span></td>
                                        <!-- <input type="hidden" id="opexo" value="0.00" name="opexo"> -->
                                    </tr>
                                <?php } ?>
                                <tr>
                                    <td style="border: none;"><?= strtoupper(lang('product_tax') . " - " . $Settings->default_tax_rate . '%:'); ?></td>
                                    <td style="border: none; padding-right:35px;" class="col-xs-2"><span id="gtax">0.00</span></td>
                                    <!-- <input type="hidden" id="imigv" value="0.00" name="imigv"> -->
                                </tr>
                                <!--***********TRJ068 - ALEXADER ROCA - 02/08/2019************-->
                                <?php if ($plastic_bags > 0) { ?>
                                    <tr>
                                        <td style="border: none;"><?= strtoupper(lang('product_tax_ICBPER') . ' (' . lang('total_bags') . '):'); ?></td>
                                        <td style="border: none; padding-right:35px;" class="col-xs-2"><span id="gtaxICBPER">0.00</span></td>
                                        <!-- <input type="hidden" id="imigv" value="0.00" name="imigv"> -->
                                    </tr>
                                <?php } ?>
                                <!--***********TRJ068 - ALEXADER ROCA - 02/08/2019************-->
                                <tr class="active">
                                    <td style="border: none"><strong><?= strtoupper(lang('importe') . " " . lang('total') . ':'); ?></strong></td>
                                    <td style="border: none; padding-right:35px;" class="col-xs-2"><strong><span id="gimptotal">0.00</span></strong></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- SECCION DISPLAY NONE -->
            <div id="customer-retainer" class="box" style="display:none; border-top: 0px solid;">
                <div class="box-body">
                    <div class="row">
                        <div class="form-group col-xs-12 col-md-2">
                            <label>Información de la retención</label>
                        </div>
                    </div>

                    <div class="row">
                        <div class="form-group col-xs-12 col-md-3">
                            Porcentaje de retención: <label id="lbl_retainer_percentage"></label>
                        </div>
                        <div class="form-group col-xs-12 col-md-3">
                            Monto de la retención: <label id="lbl_retainer_total">S/ 0.00</label>
                        </div>
                        <div class="form-group col-md-12">
                            <input type="hidden" id="retainer_percentage" value="0.00" name="retainer_percentage">
                            <input type="hidden" id="retainer_total" value="0.00" name="retainer_total">
                        </div>
                    </div>
                </div>
            </div>

            <!-- TERCERA SECCION-->
            <div class="box" style="border-top: 0px solid;">
                <div class="box-body">
                    <div class="row factura_formapago" style="display:none;">
                        <div class="form-group col-md-2">
                            <label>Forma de pago</label>
                            <?php
                            $sw = [];
                            $html_select = '<select class="form-control select2 payment_method_id" id="payment_method_id" name="payment_method_id" >';
                            $html_select = $html_select . '<option value="" data-codesunat="" >Seleccionar</option>';
                            if ($payment_methods != null) {
                                foreach ($payment_methods as $payment_method) {
                                    $html_select = $html_select . '<option value="' . $payment_method['id'] .
                                        '" data-codesunat="' . $payment_method['code_sunat'] . '" >' . $payment_method['description'] . '</option>';
                                }
                            }
                            $html_select = $html_select . '</select>';
                            ?>
                            <?= $html_select; ?>
                            <input type="hidden" name="payment_method_code_sunat" id="payment_method_code_sunat">
                        </div>
                    </div>
                    <div class="row pm_cuotas">
                        <div class="form-group col-md-4 col-md-offset-4">
                            <div class="col-md-12">
                                <div class="line line-dashed line-lg pull-in"></div>
                                <div class="row">
                                    <table class="table table-bordered" id="orders">
                                        <thead>
                                            <tr>
                                                <th>Cuota Nro</th>
                                                <th>Fecha</th>
                                                <th>Monto</th>
                                                <th>
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr id="row1">
                                                <td>
                                                    <input class="form-control pm_credit_nrocuota" type='number' id='pm_credit_nrocuota_1' name='pm_credit_nrocuota[]' for='1' value='1' readonly />
                                                </td>
                                                <td class="col-sm-4">
                                                    <input class="form-control datepicker-cuota tip pm_credit_date" type='text' data-type="pm_credit_date" id='pm_credit_date_1' name='pm_credit_date[]' for="1" />
                                                </td>
                                                <td>
                                                    <input class="form-control pm_credit_totalcuota" type='text' id='pm_credit_totalcuota_1' name='pm_credit_totalcuota[]' for='1' pattern="^\d*(\.\d{0,2})?$" data-fv-regexp-message="Sólo ingresar números con dos decimales." value='0' />
                                                </td>
                                                <td>
                                                    <button type="button" name="add" id="add" class="btn btn-success circle">+</button>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div class="line line-dashed line-lg pull-in" style="clear: both;"></div>

                            <div class="col-md-12 nopadding">
                                <div class="col-md-8 col-md-offset-6 pull-right nopadding">
                                    <div class="col-md-12 pull-right nopadding">
                                        <div class="form-group">
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <label>Total</label>
                                                </div>
                                                <div class="col-md-8">
                                                    <input class="form-control pm_credit_subtotal col-lg-8" type='text' id='pm_credit_subtotal' name='pm_credit_subtotal' readonly />
                                                </div>
                                            </div>

                                        </div>
                                    </div>
                                    <!--<div class="col-md-2 pull-right">
                                        <div class="form-group">
                                            
                                        </div>
                                    </div>-->
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col-md-12">
                            <?= lang('attachment', 'attachment'); ?>
                            <input type="file" name="userfile" class="form-control tip" id="attachment">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col-md-12">
                            <?= lang("note", 'note'); ?>
                            <?= form_textarea('note', set_value('note'), 'class="form-control redactor" id="note"'); ?>
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col-md-12">
                            <?= form_submit('add_sale', lang('add_sale'), 'class="btn btn-primary" id="add_sale"'); ?>
                            <button style="border-radius: 0px;" type="button" id="reset" class="btn btn-danger"><?= lang('reset'); ?></button>
                        </div>
                    </div>
                </div>
            </div>
            <?php echo form_close(); ?>
            <div class="clearfix"></div>
        </div>
    </div>
</section>

<!-- SECCION MODAL PARA AGREGAR CLIENTE -->
<div class="modal fade" data-easein="flipYIn" id="customerModal" tabindex="-1" role="dialog" aria-labelledby="cModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header modal-primary">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-remove"></i></button>
                <h4 class="modal-title" id="cModalLabel"><?= lang('new_customer') ?></h4>
            </div>

            <form id="customers_form">
                <input type="hidden" name="accion_cliente" value="1" id="accion-cliente">
                <input type="hidden" name="idclienteedit" value="" id="idclienteedit">
                <input type="text" hidden name="<?php echo $this->security->get_csrf_token_name(); ?>" id="token" value="<?php echo $this->security->get_csrf_hash(); ?>" />
                <input type="hidden" id="input_hidden_person_type" name="person" value="">        
                <input type="hidden" id="input_hidden_document_type" name="document_type" value=""> 
                
                <div class="modal-body">
                    <div id="alert" class="alert alert-danger text-center" style="display:none;"></div>

                    <div class="row">
                        <div class="col-md-12" id="div-cf1">
                            <div class="row">
                                <div class="col-md-6" style="margin-right: 0;padding-right: 0;">
                                    <div class="form-group ">
                                        <label class="control-label" for="cf1"><?= $this->lang->line("ccf1"); ?> *</label>
                                        <div class="input-group">
                                            <?= form_input('cf1', set_value('cf1'), 'class="form-control" id="cf1" maxlength="15"'); ?>
                                            <div class="input-group-btn">
                                                <div id="con-num-doc" class="btn btn-info" tabindex="0" data-toggle="tooltip" title="Consulta numero de documento"><i class="fa fa-search"></i></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6" style="margin: 0;padding: 0;">
                                    <div id="cargando" class="col-md-2" style="display:none;"><img style="width: 30px;height:auto;margin:0; margin-top: 150%;" src="https://pa1.narvii.com/6558/d6738388bae69543478eb78d0545bf0475ef05a6_hq.gif"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                     
                    <div class="row">
                        <div class="col-md-12" >
                            <div class="form-group" id="div-person_type">
                                <label class="control-label" for="type_persona"><?= $this->lang->line("type_person"); ?> *</label>
                                <div class="radio-group">
                                    <div class="radio-inline">
                                        <input type="radio" checked="true" name="person" id="person-natural" value="1" class="radio-person-type mg">
                                        <label class="custom-control-label"><?= $this->lang->line("person1"); ?></label>
                                    </div>
                                    <div class="radio-inline">
                                        <input type="radio" name="person" id="person-juridica" value="2" class="radio-person-type">
                                        <label class="custom-control-label"><?= $this->lang->line("person2"); ?></label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    
                    <div class="row">
                        <div class="col-md-12" id="div-document_type">
                            <div class="form-group">
                                <?= lang('document_type', 'document_type'); ?> *
                                <select name="document_type" id="document-type" class="form-control" >
                                    <option value=""><?= lang("select") . " " . lang("document_type") ?></option> 
                                <?php
                                    foreach ($document_type as $doc_type) { ?>
                                        <option value="<?= $doc_type->id ?>"><?= $doc_type->document_type; ?></option> 
                                    <?php }?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12" id="div-cf2">
                            <div class="row">
                                <div class="col-md-6" style="margin-right: 0;padding-right: 0;">
                                    <div class="form-group">
                                        <label class="control-label" for="cf2"><?= $this->lang->line("ccf2"); ?> </label>
                                        <div class="input-group">
                                            <?= form_input('cf2', set_value('cf2'), 'class="form-control" id="cf2" maxlength="11" oninput="this.value = this.value.replace(/[^0-9.]/g, \'\').replace(/(\..*)\./g, \'$1\');"'); ?>
                                            <div class="input-group-btn">
                                                <div id="con-ruc" class="btn btn-info" tabindex="0" data-toggle="tooltip" title="Consulta numero de documento"><i class="fa fa-search"></i></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6" style="margin: 0;padding: 0;">
                                    <div id="cargando-ruc" class="col-md-2" style="display:none;"><img style="width: 30px;height:auto;margin-top:150%" src="https://pa1.narvii.com/6558/d6738388bae69543478eb78d0545bf0475ef05a6_hq.gif"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-xs-12">
                            <div class="form-group">
                                <label class="control-label" id="nombre-persona" for="code"><?= lang("name"); ?></label>
                                <?= form_input('name', '', 'class="form-control input-sm kb-text" id="name" maxlength="150"'); ?>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-6">
                            <div class="form-group">
                                <label class="control-label" for="cemail">
                                    <?= lang("email_address"); ?>
                                </label>
                                <?= form_input('email', '', 'class="form-control input-sm kb-text" id="cemail" maxlength="100"'); ?>
                            </div>
                        </div>
                        <div class="col-xs-6">
                            <div class="form-group">
                                <label class="control-label" for="phone"><?= $this->lang->line("phone_movil"); ?></label>
                                <div class="input-group" style="width: 100%;">
                                    <select id="codigoPais" name="codigoPais" class="form-control" style="width: 35%; margin-right: 5px;">
                                        <option value="51"><img src="<?= $assets ?>images/peru.png"/>(PE)+51</option>
                                    </select>
                                    <?= form_input('phone', set_value('phone',(isset($form_data['phone'])?preg_replace('/^51/', '',$form_data['phone']):"")), 'class="form-control" style="width: 62%;" oninput="this.value = this.value.replace(/[^0-9.]/g, \'\').replace(/(\..*)\./g, \'$1\');" id="phone" maxlength="15"'); ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xs-12">
                            <div class="form-group">
                                <label class="control-label" for="direccion">
                                    <?= lang("address"); ?>
                                </label>
                                <?= form_input('direccion', '', 'class="form-control input-sm kb-text" id="cdireccion" maxlength="255"'); ?>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
						<?= lang('customers_type', 'customers_type'); ?>
						<?php
						
						$ctv[0] = lang("select") . " " . lang("customers_type");
						foreach ($list_customer_type as $cust_type) {
							$ctv[$cust_type['id']] = $cust_type['customers_type'];
						}
						?>

						<!--********** TRJ124***** -->
						<!-- AMADOR -->
						<?= form_dropdown('customer_type', $ctv, set_value("type", $list_customer_type[0]['customers_type']), 'class="form-control select2" id="customer_type" style="width:100%;"');
						?>
						<!-- END -->
					</div>
                </div>
                <div class="modal-footer" style="margin-top:0;padding-top: 0px;border-top:0px;">

                    <button type="button" class="btn btn-primary" style="border-radius: 0px;" id="add_customer"> <?= lang('accept') ?> </button>
                    <button type="button" class="btn btn-default" style="border-radius: 0px;" data-dismiss="modal"> <?= lang('cancel') ?> </button>

                </div>
            </form>
        </div>
    </div>
</div>
<!-- FIN DEL MODAL -->

<input type="hidden" id="fflag" value="1">
<input type="hidden" id="exchange" value="<?= $Exchange->sell ?>">
<script src="<?= $assets ?>plugins/bootstrap-datetimepicker/js/moment.min.js" type="text/javascript"></script>
<script src="<?= $assets ?>plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js" type="text/javascript"></script>
<script src="<?= $assets ?>dist/js/jquery-ui.min.js" type="text/javascript"></script>
<script src="<?= $assets ?>plugins/input-mask/jquery.inputmask.js" type="text/javascript"></script>
<script src="<?= $assets ?>plugins/input-mask/jquery.inputmask.date.extensions.js" type="text/javascript"></script>
<script src="<?= $assets ?>plugins/select2/select2.min.js" type="text/javascript"></script>
<script src="<?= $assets ?>dist/js/sales-customers.js" type="text/javascript"></script>
<script src="<?= $assets ?>dist/js/pages/Customers.js" type="text/javascript"></script>
<script src="<?= $assets ?>dist/js/pages/sales.js" type="text/javascript"></script>
<script src="<?= $assets ?>dist/js/jquery-ui.min.js" type="text/javascript"></script>

<script type="text/javascript">
    var avdSale = <?= $advance_sale ?>; //Define si esta activo la venta avanzada
    $(function() {
        var today = new Date();
        var min = new Date().setDate(today.getDate() - 3);
        // var in_a_week   =new Date().setDate(today.getDate()+7);
        // var min_ex = new Date().setDate($("#date").val());
        var rowCount = 1;

        $('.datepicker').datetimepicker({
            format: 'YYYY-MM-DD'
        });

        $('.datepicker-cuota').datetimepicker({
            format: 'YYYY-MM-DD',
            minDate: new Date().setDate(today.getDate() + 1)
        });

        $('.datetimepicker').datetimepicker({
            format: 'YYYY-MM-DD',
            maxDate: today,
            minDate: min //restingue fecha en la que se genera una factura - solicitud especial viccar
        });

        // SOLO SI LA FORMA DE PAGO ES "factura" SE HABILITA

        $('#factura_formapago').show();
        $(".payment_method_id").val('1').change();

        $('#document_type').on('change', function() {
            $('.factura_formapago').show();
            $(".payment_method_id").val('1').change();
            var customerIsRetainer = $("#customer").data('isretainer');
            var customerRetainerPercentage = $("#customer").data('retainerpercentage');
            console.log(customerIsRetainer,customerRetainerPercentage);
            // ********START TRJ143 - DANIEL PADILLA - 20/12/2022*****************
            showHideRetainer(customerIsRetainer,customerRetainerPercentage);
            // ********END TRJ143 - DANIEL PADILLA - 20/12/2022***************** 
        });

        // FORMA DE PAGO
        var val_code_sunat = $('.payment_method_id').find(':selected').attr('data-codesunat');
        mostrar_ocultar_divcuotas();
        $('#payment_method_code_sunat').val(val_code_sunat);
        get_codesunat_from_paymentmethod();

        function mostrar_ocultar_divcuotas() {
            var val_paymentmethod = $('.payment_method_id').find(':selected').text();
            if (val_paymentmethod.toLowerCase() == "crédito" || val_paymentmethod.toLowerCase() == "credito") {
                var val_gimptotal = parseFloat($("#gimptotal").val());
                // <!--********START TRJ143 - DANIEL PADILLA - 20/12/2022***************** -->
                val_gimptotal = getTotalWithRetention(val_gimptotal);
                // <!--********END TRJ143 - DANIEL PADILLA - 20/12/2022***************** -->

                $('.pm_cuotas').show();
                $('#pm_credit_totalcuota_1').val(val_gimptotal.toFixed(2));
                $('#pm_credit_totalcuota_1').trigger('input');
            } else {
                $('#pm_credit_date_1').val('');
                $('#pm_credit_totalcuota_1').val(0);
                for (i = 2; i <= rowCount; i++) {
                    $('#row' + i).remove();
                }
                $('#pm_credit_subtotal').val(0);
                $('.pm_cuotas').hide();
            }
        }
        // FORMA DE PAGO

        // CREDITO
        //var rowCount = 1;
        $('#add').click(function() {
            var html_row = "";
            var cant_rows = $('#orders').find('tbody tr').length;
            rowCount++;
            html_row += '<tr id="row' + rowCount + '">';
            html_row += '   <td><input class="form-control pm_credit_nrocuota" type="number" id="pm_credit_nrocuota_' + rowCount + '" name="pm_credit_nrocuota[]" for="' + rowCount + '" value="' + (cant_rows + 1) + '" readonly/></td>';
            html_row += '   <td><input class="form-control datepicker-cuota tip pm_credit_date" type="text" data-type="pm_credit_date" id="pm_credit_date_' + rowCount + '" name="pm_credit_date[]" for="' + rowCount + '"/></td>';
            html_row += '   <td><input pattern="^\\d*(\\.\\d{0,2})?$" data-fv-regexp-message="Sólo ingresar números con dos decimales." class="form-control pm_credit_totalcuota" type="text" id="pm_credit_totalcuota_' + rowCount + '" name="pm_credit_totalcuota[]"  for="' + rowCount + '" value="0"/> </td>';
            html_row += '   <td><button type="button" name="remove" id="' + rowCount + '" class="btn btn-danger btn_remove cicle">-</button></td>';
            html_row += '</tr>';
            $('#orders').append(html_row);

            $('.datepicker-cuota').datetimepicker({
                format: 'YYYY-MM-DD',
                minDate: new Date().setDate(today.getDate() + 1)
            });
            $('#pm_credit_date_' + rowCount).val('');
            var gimptotal = parseFloat(parseFloat($("#gimptotal").val()).toFixed(2));
            var pm_credit_subtotal = parseFloat(parseFloat($('#pm_credit_subtotal').val()).toFixed(2));
            if (gimptotal >= pm_credit_subtotal) {
                var saldo_restante = gimptotal - pm_credit_subtotal;
                $('#pm_credit_totalcuota_' + rowCount).val(saldo_restante.toFixed(2)).trigger('input');
            }
        });

        $("#orders").on('input', 'input.pm_credit_totalcuota', function() {
            calculateSubTotal();
        });

        $(document).on('click', '.btn_remove', function() {
            var button_id = $(this).attr('id');
            var total_cuota = $('#pm_credit_totalcuota_' + button_id).val();
            var subtotal = $('#pm_credit_subtotal').val();
            if (total_cuota != "") {
                subtotal = subtotal - total_cuota;
                $('#pm_credit_subtotal').val(subtotal.toFixed(2));
            }
            $('#row' + button_id + '').remove();
            $('.pm_credit_nrocuota').each(function(k, v) {
                $(this).val(k + 1);
            });
        });

        function get_codesunat_from_paymentmethod() {
            $('.payment_method_id').on('change', function() {
                var val_code_sunat = $(this).find(':selected').attr('data-codesunat');
                $('#payment_method_code_sunat').val(val_code_sunat);
                mostrar_ocultar_divcuotas();
            });
        }

        function calculateSubTotal() {
            var subtotal = 0;
            $('.pm_credit_totalcuota').each(function() {
                var total_cuota = $(this).val();
                if (total_cuota != "") {
                    subtotal += parseFloat(total_cuota);
                }
            });
            var subtotal = parseFloat(subtotal);
            $('#pm_credit_subtotal').val(subtotal.toFixed(2));
        }
        // CREDITO

        // VALIDACION
        /*$('.validation').formValidation(
            { 
                framework: 'bootstrap', 
                excluded: ':disabled',
                fields: {
                    pm_credit_totalcuota: {
                        enabled: true,
                        validators: {
                            integer: {
                                'default': 'lkjlknml'
                            }
                        }
                    }
                }
            }
        );*/
    
     // HH:mm

        if (get('remove_spo')) {
            if (get('spoitems')) {
                remove('spoitems');
            }
            remove('remove_spo');
        }
        <?php if ($this->session->userdata('remove_spo')) { ?>
            if (get('spoitems')) {
                remove('spoitems');
            }
        <?php $this->tec->unset_data('remove_spo');
        } ?>

        function attach(x) {
            if (x !== null) {
                return '<a href="<?= base_url(); ?>uploads/' + x + '" target="_blank" class="btn btn-primary btn-block btn-xs"><i class="fa fa-chain"></i></a>';
            }
            return '';
        }

        $('form').keypress(function(e) {
            if (e == 13) {
                return false;
            }
        });

        $(document).on('keypress', 'input', function(e) {
            if (e.which == 13) {
                return false;
            }
        });

        /*$('input').keypress(function(e){
            if(e.which == 13){
            return false;
            }
        });*/
        
        
        if ($('#person-natural').is(':checked')) {
            $('#document-type option[value="6"]').prop('disabled', true);
        }							

        if ($('#person-juridica').is(':checked')) {
            $("#div-document_type *").prop("disabled", true);
            $('#doctypejs').val(6);
            $('#document-type').val(6).trigger('change.select2');
        }
    });
    
    var spoitems = {};
        var plastic_bags = '<?= $plastic_bags; ?>';
        var lang = new Array();
        lang['code_error'] = '<?= lang('code_error'); ?>';
        lang['r_u_sure'] = '<?= lang('r_u_sure'); ?>';
        lang['no_match_found'] = '<?= lang('no_match_found'); ?>';
        lang['products_not_found'] = '<?= lang('products_not_found') ?>';
        lang['sale_not_less'] = '<?= lang('sale_not_less') ?>';
        lang['verify_ruc'] = '<?= lang('verify_ruc') ?>';
        lang['verify_dniRuc'] = '<?= lang('verify_dniRuc') ?>';
        lang['verify_address'] = '<?= lang('verify_address') ?>';
        lang['aviso_tax_ICBPER'] = '<?= lang('aviso_tax_ICBPER') ?>';
</script>

<!-- <script>
    $('#customer').on('click', function() {
        // Muestra todos los elementos de la lista al hacer clic en el input
        $('#lista li').show();
    });
    $(document).on('click', function(event) {
        // Oculta todos los elementos de la lista al hacer clic fuera del input
        if (!$(event.target).closest('#customer').length) {
            $('#lista li').hide();
        }
    });
    $('#customer').on('input', function() {
        var searchTerm = $(this).val();
        $.ajax({
            url: 'get_customers/' + encodeURIComponent(searchTerm),
            dataType: 'json',
            type: 'GET',
            success: function(data) {
                $('#lista').empty();
                $.each(data, function(index, customer) {
                    var listItem = $('<li>')
                        .text(customer.name)
                        .attr('data-customer-id', customer.id)
                        .attr('data-isretainer', customer.is_retainer)
                        .attr('data-retainerpercentage', customer.retainer_percentage)
                        .attr('data-customertype', customer.customers_type_id);
                    listItem.appendTo('#lista');
                    listItem.on('click', function() {
                        // console.log('Seleccionaste:', customer.name);
                        var customerId = customer.id;
                        var customerName = customer.name;
                        // Establecer el ID y el nombre del cliente en inputs ocultos
                        $('#customer_id').val(customerId);
                        $('#customer_name').val(customerName);
                        // Establecer el nombre del cliente en el input visible
                        $('#customer').val(customerName);
                        // Ocultar la lista de clientes
                        $('#lista').hide();
                        // Verifica si se asignó un valor al input #customer y muestra en la consola
                        console.log('ID del cliente seleccionado:', customerId);
                    });
                });
            },
            error: function(xhr, status, error) {
                console.error('Error en la solicitud AJAX:', status, error);
            }
        });
    });
</script> original-->

<!-- <script>
    $('#customer').on('click', function() {
        $('#lista li').show();
    });

    $(document).on('click', function(event) {
        if (!$(event.target).closest('#customer').length) {
            $('#lista li').hide();
        }
    });
    
    $('#customer').on('input', function() {
        var searchTerm = $(this).val();

        $.ajax({
            url: 'get_customers/' + encodeURIComponent(searchTerm),
            data: { q: searchTerm },
            dataType: 'json',
            type: 'GET',
            delay: 250,
            success: function(data) {
                //console.log('Datos recibidos:', data);
                var listHTML = '';

                $.each(data, function(index, customer) {
                    //console.log('Cliente:', customer);
                    listHTML += '<li data-customer-id="' + customer.id + '" data-isretainer="' + customer.is_retainer + '" data-retainerpercentage="' + customer.retainer_percentage + '" data-customertype="' + customer.customers_type_id + '">' + customer.name + '</li>';
                });
                //console.log('HTML de la lista:', listHTML);

                $('#lista').html(listHTML);

                // Manejar clic en elementos de la lista
                $('#lista li').on('click', function() {
                    var customerId = $(this).data('customer-id');
                    var customerName = $(this).text();

                    $('#customer_id').val(customerId);
                    $('#customer_name').val(customerName);
                    $('#customer').val(customerName);
                    // $('#lista').hide();
                    //console.log('ID del cliente seleccionado:', customerId);
                });
            },
            error: function(xhr, status, error) {
                console.error('Error en la solicitud AJAX:', status, error);
            }
        });
    });
</script> -->

<script>
    $('#customer').on('click', function() {
        $('#lista li').show();
    });

    $(document).on('click', function(event) {
        if (!$(event.target).closest('#customer').length) {
            $('#lista li').hide();
        }
    });

    var debounceTimer;

    $('#customer').on('keyup', function() {
        $('#customer_id').val('');
        $('#customer_name').val('');
        $('#customer_is_retainer').val('');
        $('#customer_retainer_percentage').val('');
        $('#customer_type').val('');
        $("#customer").data("isretainer", '');
        $("#customer").data("retainerpercentage", '');
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function() {
            var searchTerm = $('#customer').val().trim();
            if (searchTerm !== '') {
                $.ajax({
                    url: 'get_customers/' + (searchTerm.replace(/ /g, "-")),
                    dataType: 'json',
                    type: 'GET',
                    success: function(data) {
                        var listHTML = '';
                        $.each(data, function(index, customer) {
                            listHTML += '<li data-customer-id="' + customer.id + '" data-isretainer="' + customer.is_retainer + '" data-retainerpercentage="' + customer.retainer_percentage + '" data-customertype="' + customer.customers_type_id + '">' + customer.name + '</li>';
                        });
                        $('#lista').html(listHTML);
                        $('#lista li').on('click', function() {
                            var customerId = $(this).data('customer-id');
                            var customerName = $(this).text();
                            var customerIsRetainer = $(this).data('isretainer');
                            var customerRetainerPercentage = $(this).data('retainerpercentage');
                            var customerType = $(this).data('customertype');
                            $('#customer_id').val(customerId);
                            $('#customer_name').val(customerName);
                            $('#customer_is_retainer').val(customerIsRetainer);
                            $('#customer_retainer_percentage').val(customerRetainerPercentage);
                            $('#customer_type').val(customerType);
                            $('#customer').val(customerName);
                            $("#customer").data("isretainer", customerIsRetainer);
                            $("#customer").data("retainerpercentage", customerRetainerPercentage);

                            console.log(customerId+' - '+customerName+' - '/*+customerIsRetainer+' - '+customerRetainerPercentage+' - '*/+customerType);
                            showHideRetainer(customerIsRetainer,customerRetainerPercentage);
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error('Error en la solicitud AJAX:', status, error);
                    }
                });
            } else {
                $('#lista').empty();
            }
        }, 500); 
    });
</script>
