<?php (defined('BASEPATH')) OR exit('No direct script access allowed'); ?>

<script>
    $(window).load(function () {
        $('.mm_guides').addClass('active');
        <?php if($guide_type == "S"){ ?>
            $('#guides_departure').addClass('active');
        <?php }else{ ?>
            $('#guides_entrance').addClass('active');
        <?php } ?>
    });
</script>
<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box" style="border-top: 2.5px solid #9fc10b;">
                <!-- <div class="box-header">
                    <h3 class="box-title"><?= lang('enter_info'); ?></h3>
                </div> -->
                <div class="box-body">
                    <div class="col-lg-12">
                        <?php
                            $attrib = array('class' => 'validation', 'role' => 'form', 'name'=>'formGuide', 'id'=>'formGuide');
                            $hidden = array(
                                            'tec_guide_id' => $id,
                                            'guide_type'=>$guide_type,
                                            'local_id'=> $local_id,
                                            'userguide_id'=> $uCrea
                                        );
                            if($id == '')
                            {
                                echo form_open("guides/new", $attrib,$hidden);
                            }
                            else
                            {
                                echo form_open("guides/update/".$id, $attrib,$hidden); 
                            }
                        ?>
                        <?php 
                        
                        if($msn != null){
                            if($msn['result']=='ok'){
                                echo '<div class="alert a alert-info alert-dismissible" role="alert">';
                                echo ' <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
                                echo $msn['message'];
                                echo '</div>';
                            }
                            if($msn['result']=='failed'){
                                if(is_array($msn['message'])){
                                    $m =$msn['message'];
                                    echo '<div class="alert a alert-danger alert-dismissible" role="alert">';
                                    echo ' <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><ul>';
                                    
                                    foreach($m as $item => $valor){
                                        foreach ($valor as $cont){
                                            echo '<li>'.$cont.'</ul>';
                                        }
                                    }
                                    echo'</ul></div>';
                                } else{
                                    echo '<div class="alert a alert-danger alert-dismissible" role="alert">';
                                    echo ' <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
                                    echo $msn['message'];
                                    echo '</div>';
                                }  
                            }
                        };  
                    ?>
                        
                        <input type="hidden" name="supplier_name" id="supplier_name">
                        <input type="hidden" name="customer_name" id="customer_name">
                        <input type="hidden" name="warehouse_name" id="warehouse_name" value="<?php echo $warehouse_name; ?>">
                        <input type="hidden" name="warehouseguide_detail" id="warehouseguide_detail">
                        <div class="row">
                            <div class="col-md-12">
                                <fieldset class="warehouse-border">
                                <legend class="warehouse-border"><?= lang("guide", "guide"); ?></legend>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <?= lang('warehouse_s', 'warehouse_s'); ?>
                                                <?php
                                                    // $arryProduct[] = lang("select")." ".lang("warehouse");
                                                    $arrayWarehouses['']= lang("select")." almacén";
                                                    foreach($warehouses as $warehouse) {
                                                        $arrayWarehouses[$warehouse['id']] = $warehouse['warehouse'];
                                                    }
                                                ?>
                                                <?= form_dropdown('warehouse_id',$arrayWarehouses,set_value("type",$warehouse_id),'class="form-control"  id="warehouse_id"  required="required" style="width:100% !important;"');
                                                ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <label for="dateinput">Fecha</label>
                                            <div class='input-group date' id='divFechaInicio'>
                                                <input type='text' id="dateinput" name="date" class="input-medium form-control" placeholder="dd/mm/aaaa" readonly />
                                                <span class="input-group-addon">
                                                    <span class="fa fa-calendar glyphicon glyphicon-calendar"></span>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="fechatras">Fecha tras</label>
                                                <div class="input-group date" id="divFechatras">
                                                    <input class="input-medium form-control" type="text" id="fechatras" name="date_tras" placeholder="dd/mm/aaaa" readonly>
                                                    <span class="input-group-addon" id="calendarioEnvio">
                                                        <span class="fa fa-calendar glyphicon glyphicon-calendar"></span>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-4" >
                                            <div class="form-group">
                                                <?= lang('payment_methods', 'payment_methods'); ?>
                                                <?php
                                                $arraypayment_methods['']= lang("select")." forma de pago";
                                                foreach($payment_methods as $payment_method) {
                                                $arraypayment_methods[$payment_method['id']] = $payment_method['description'];
                                                }
                                                ?>
                                                <?= form_dropdown('payment_method_id',$arraypayment_methods,set_value("type",$payment_method_id),'class="form-control"  id="payment_method_id" name="payment_method_id" required="required" style="width:100% !important;"');
                                                ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="order_number">Número de pedido</label>
                                                <?php echo form_input('order_number', $order_number, 'class="form-control input-alpha" id="order_number" name="order_number" required="required"'); ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="docreference_number">Número documento ref.</label>
                                                <?php echo form_input('docreference_number', $docreference_number, 'class="form-control input-alpha" id="docreference_number" name="docreference_number" required="required"'); ?>
                                            </div>
                                        </div>
                                        
                                    </div>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <?=lang("select_Supplier/Customer", "select_Supplier/Customer") ?>
                                                <?php
                                                $arraycustomerSupplier['']= lang("select");
                                                $arraycustomerSupplier[1]= lang("supplier");
                                                $arraycustomerSupplier[2]= lang("customer");
                                              
                                                ?>
                                                <?= form_dropdown('prov_cli',$arraycustomerSupplier,set_value("type",$prov_cli),'class="form-control selectProvCli"  id="prov_cli" name="prov_cli"  style="width:100% !important;"');
                                                ?>
                                            </div>
                                        </div>
                                        <div class="col col-md-4" id="cliDiv">
                                            <div class="form-group">
                                                <?= lang('customers','customers'); ?>
                                                <?php
                                                $arraycustomer['']= lang("select")." ".strtolower(lang("customer"));
                                                foreach($customers as $customer) {
                                                $arraycustomer[$customer['id']] = $customer['name'];
                                                }
                                                ?>
                                                <?= form_dropdown('customer_id',$arraycustomer,set_value("type",$customer_id),'class="form-control selectProvCli"  id="select_cli" name="customer_id"  style="width:100% !important;"');
                                                ?>
                                            </div>
                                        </div>
                                        <div class="col col-md-4"  id="provDiv">
                                            <div class="form-group">
                                                <?= lang('suppliers','suppliers'); ?>
                                                <?php
                                                $arraysupplier['']= lang("select")." ".strtolower(lang("supplier"));
                                                foreach($suppliers as $supplier) {
                                                $arraysupplier[$supplier['id']] = $supplier['name'];
                                                }
                                                ?>
                                                <?= form_dropdown('supplier_id',$arraysupplier,set_value("type",$supplier_id),'class="form-control selectProvCli"  id="select_prov" name="supplier_id"  style="width:100% !important;"');
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-4" id="counterDiv">
                                            <div class="form-group">
                                                <?= lang('counter', 'counter'); ?>
                                                <?php
                                                    $arraycounter['']= lang("select")." ".lang("counter");
                                                    $arraycounter['interno']= lang("Interno");
                                                    $arraycounter['externo']= lang("Externo");
                                                    foreach($counter as $counter) {
                                                    $arraycounter[$counter['id']] = $counter['code']."-".$counter['description'];
                                                    }
                                                ?>
                                                <?= form_dropdown('counter',$arraycounter,set_value("type",$counter),'class="form-control"  id="counter" name="counter"  style="width:100% !important;"');
                                                ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="guide_number">Nº de guía</label>
                                                <?php
                                                    if($guide_type == "S"){
                                                        $required='';
                                                        $disable = 'readonly="true"';
                                                    }else{
                                                        $required='required="required"';
                                                        $disable = '"';
                                                    }
                                                    echo form_input('guide_number', $guide_number, 'class="form-control input-alpha" id="guide_number" name="guide_number" '.$required.' '.$disable); 
                                                ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <?= lang('type_movement_s', 'type_movement_s'); ?>
                                                <?php
                                                    $arraytypes_movement['']= lang("select")." tipo de movimiento";
                                                    foreach($types_movement as $types_movement) {
                                                    $arraytypes_movement[$types_movement['id']] = $types_movement['alias']."-".$types_movement['motive'];
                                                    }
                                                ?>
                                                <?= form_dropdown('movement_type_id',$arraytypes_movement,set_value("type",$movement_type_id),'class="form-control"  id="types_movement_id" name="movement_type_id"  style="width:100% !important;"');
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <?= lang('currency_name', 'currency_name'); ?>
                                                <?php
                                                    $arraycurrency['']= lang("select")." ".strtolower(lang("currency_name"));
                                                    $arraycurrency['USD']= lang("currency_usd");
                                                    $arraycurrency['PEN']= lang("currency_pen");
                                                    foreach($currency as $currency) {
                                                    $arraycurrency[$currency['id']] = $currency['code']."-".$currency['description'];
                                                    }
                                                ?>
                                                <?= form_dropdown('currency',$arraycurrency,set_value("type",$currency),'class="form-control"  id="currency" name="currency"  style="width:100% !important;"');
                                                ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="exchange">Tipo de cambio:</label>
                                                <?php echo form_input('exchange', $exchange, 'class="form-control input-alpha" id="exchange" name="exchange" required="required"'); ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <label for="observation">Comentario:</label>
                                            <textarea name="observation" maxlength="250" cols="40" rows="3" 
                                                class="form-control input-alpha" id="observation"></textarea>
                                        </div>
                                    </div>
                                </fieldset>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-2">
                                <div class="form-group">
                                   <a href="" class="btn btn-warning btn-edit form-control" data-toggle="modal" data-target="#myModal" data-id="0" id="addPrdNew"> <?=  lang('add_product'); ?></a>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="table-responsive">
                                    <table id="listados" class="table table-striped table-bordered table-condensed table-hover" style="width:100%">

                                    </table>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <hr>
                            </div>
                        </div>
                        <fieldset class="warehouse-border">
                            <legend class="warehouse-border"><?= lang("guide_resume", "guide_resume"); ?></legend>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-inline">
                                        <div class="form-group">
                                            <div class="col-md-2">
                                            <label for="itemResume">Items:</label>
                                            </div>
                                            <div class="col-md-6">
                                            <input type="number" class="form-control" id="itemResume" disabled>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="col-md-2">
                                            <label for="itemResume">Cant:</label>
                                            </div>
                                            <div class="col-md-6">
                                            <input type="number" class="form-control" id="cantTotResume" disabled>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="col-md-2">
                                            <label for="itemResume">Total:</label>
                                            </div>
                                            <div class="col-md-6">
                                            <input type="number" class="form-control" id="totResume" disabled>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                        <div class="row">
                            <div class="col-md-12">
                                <hr>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-2" style="float: right;">
                                <div class="form-group" >
                                    <?php
                                        if($id == '')
                                        {
                                            //echo '<input type="submit" class="btn btn-primary" value="store">';
                                            echo form_submit('save_guide', lang('save_guide'), 'class="btn btn-primary form-control"');
                                        }
                                        else
                                        {
                                            echo form_submit('update', lang('update').' '.lang('guide'), 'class="btn btn-success form-control"');
                                        }
                                    ?>
                                </div>
                            </div>
                            <div class="col-md-2" style="float: right;">
                                <div class="form-group">
                                <?php
                                    if($guide_type == "S"){
                                        echo '<a href="'.site_url('guides_departure/s') .'"  class="btn btn-danger form-control">'. lang('close').'</a>';

                                    }else{
                                        echo '<a href="'.site_url('guides_entrance/i') .'"  class="btn btn-danger form-control">'. lang('close').'</a>';
                                    } 
                                ?>
                                </div>
                            </div>
                        </div>
                        
                        <?php echo form_close(); ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal add Products -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div id="loader"></div>
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4>Registro: <span id="descDoc"></span></h4>
                
                </div>
                <div class="modal-body">
                    <?php echo form_open(); ?>
                    <input type="hidden" id="idReg" name="idReg">
                    <input type="hidden" id="name" name="name">
                    <input type="hidden" id="idSerie" name="idSerie">
                    <input type="hidden" id="tec_register_guide_id" name="tec_register_guide_id">
                    <fieldset class="warehouse-border">
                    <legend class="warehouse-border"><?= lang("product", "product"); ?></legend>
                        <div class="form-group">
                            <div class="col-md-10">
                                    <!-- <label for="product_id"><?php //lang('products', 'products'); ?></label>
                                    <select class="form-control" id="productSelect" name="product_id" required="required" style="width:100% !important;">
                                    <option>Seleccione un producto</option>
                                    <?php
                                        // foreach($products as $product){
                                        //     echo "<option value='".$product['id']."'> ".$product['code']."-".$product['name']."</option>";
                                        // }
                                    ?>
                                    </select> -->
                                <div class="form-group">
                                    <?= lang('select_product', 'select_product'); ?>
                                    <?php
                                        $arrayproducts['']= lang("select")." ".lang("product");
                                        foreach($products as $product) {
                                            $arrayproducts[$product['id']] = $product['code']."-".$product['name'];
                                        }
                                    ?>
                                    <?= form_dropdown('productSelect',$arrayproducts,'','class="form-control"  id="productSelect" name="product_id"  style="width:100% !important;"');
                                    ?>
                                </div>
                            </div>

                            <div class="col-md-2">
                                <label for="quantity"> <?= lang('quantity'); ?></label>
                                <input type="number" class="form-control" id="quantity" min="0" name="quantity" value='0' placeholder="<?= lang('quantity'); ?>" required>
                            </div>
                        </div>
                        <div class="form-group" >
                            <div class="col-md-3">
                                <label for="price">   <?= lang('cost', 'cost'); ?></label>
                                <input type="number" class="form-control" id="price" min="0" name="price" value="0" placeholder="<?= lang('price'); ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label for="avgdiscount">   <?= lang('avgdiscount', 'avgdiscount'); ?> [%]</label>
                                <input type="number" class="form-control" id="avgdiscount" min="0" max="100" name="avgdiscount" value="0" placeholder="<?= lang('avgdiscount'); ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label for="price_inc">   <?= lang('cost_inc', 'cost_inc'); ?></label>
                                <input type="number" class="form-control" id="price_inc" name="price_inc" value="0" placeholder="<?= lang('price_inc'); ?>" disabled>
                            </div>
                            <div class="col-md-3">
                                <label for="total">   <?= lang('total', 'total'); ?></label>
                                <input type="number" class="form-control" id="total" name="total"  placeholder="<?= lang('total'); ?>" disabled>
                            </div>
                        </div>
                    </fieldset>
                    <div id="lotDiv">
                        <fieldset class="warehouse-border">
                        <legend class="warehouse-border"><?= lang("Lote", "Lote"); ?></legend>
                            <div class="form-group" >
                                <div class="col-md-12">
                                    <label for="lot_number">   <?= lang('lot_number', 'lot_number'); ?></label>
                                    <input type="text" class="form-control" id="lot_number" name="lot_number" placeholder="<?= lang('lot_number'); ?>" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-6">
                                    <label for="production_date">   <?= lang('production_date', 'production_date'); ?></label>
                                    <div class="input-group date" id="calendar_lot_from">
                                        <input class="input-medium form-control" type="text" id="production_date" placeholder="dd/mm/aaaa" readonly>
                                        <span class="input-group-addon" id="calendarioFechaLote">
                                            <span class="fa fa-calendar glyphicon glyphicon-calendar"></span>
                                        </span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label for="expiration_date">   <?= lang('expiration_date', 'expiration_date'); ?></label>
                                    <div class="input-group date" id="calendar_lot_to">
                                        <input class="input-medium form-control" type="text" id="expiration_date" name="expiration_date" placeholder="dd/mm/aaaa" readonly>
                                        <span class="input-group-addon" id="calendarioFechaLote2">
                                            <span class="fa fa-calendar glyphicon glyphicon-calendar"></span>
                                        </span>
                                    </div>
                                </div>
                                
                            </div>
                        </fieldset>
                    </div>
                    <div id="serialDiv">
                        <fieldset class="warehouse-border">
                        <legend class="warehouse-border"><?= lang("Serie", "Serie"); ?></legend>
                            <div class="form-group" >
                                <div class="col-md-12">
                                    <div style="width: 200px ;">
                                        <label for="serial_number">   <?= lang('enter_serial_number', 'enter_serial_number'); ?></label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="serial_number" name="serial_number" placeholder="<?= lang('enter_serial_number'); ?>" >
                                            <span class="input-group-btn">
                                                <button class="btn btn-default" id="btnAddSerial" type="button"> <i class="fa fa-plus" aria-hidden="true"></i> </button>
                                            </span>
                                        </div><!-- /input-group -->
                                    </div><!-- /.col-lg-6 -->
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <div id="col_seriales" class="col_seriales">  
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                    </div>
                    <fieldset class="warehouse-border">
                    <legend class="warehouse-border"><?= lang("observations", "observations"); ?></legend>
                        <div class="form-group">
                            <div class="col-md-12">
                                <textarea rows="2" class="form-control" name="observation_reg" id="observation_reg" placeholder="<?= lang('observations'); ?>" ></textarea>
                            </div>
                            <br>
                        </div>
                    </fieldset>
                   
                </div>
                <?php echo form_close(); ?>

                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"><?=lang('close')?> </button>
                    <button type="button" class="btn btn-primary" id="btn_send_form"> <?=lang('save')?> </button>
                </div>
            </div>
        </div>
    </div>
    <!-- END Modal add Products -->
</section>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js" type="text/javascript"></script>

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="<?= $assets ?>plugins/datatables/datatable.min.js"></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/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>
        var dataCol =  '<?= $details?>';
        
        if(dataCol == "" || dataCol == "null"){
            dataCol = [];
        }else{
            dataCol =  JSON.parse(dataCol);
            dataCol.forEach( function(valor, indice, array) {
                array[indice].expiration_date = array[indice].expiration_date.indexOf("-0001") == "-1" ? array[indice].expiration_date : '';
                array[indice].production_date = array[indice].production_date.indexOf("-0001") == "-1" ? array[indice].expiration_date : '';
            });
        }
        var idReg = '';
        var urlSerie = "<?= site_url('series/get') ?>"+'/';
        var prov_cli = "<?= $prov_cli ?>";
        var userguide_id = parseFloat("<?= $userguide_id ?>");
        var warehouseguide_id = "<?= $id ?>";
        var local_id = "<?= $local_id ?>";
        var userguide_id = "<?= $userguide_id ?>";
        var igv = parseFloat("<?= $igv ?>");
        if(igv == ""){
            igv = 0;
        }else{
            igv = parseFloat(igv);
        }
        // alert("Local id:"+local_id+" y el userguide_id es: "+userguide_id);
        var guide_type = "<?= $guide_type ?>";
        var document_type_id=0;
        var price = 0;
        var name ='';
        var avgdiscount = 0;
        var total=0;
        var quantity=0;
        var series=[];
        var haySerie = 0;
        var hayLote = 0;
        var product_id = $( "#productSelect" ).val();
        var cantProd=0;
        var cantItem=0;
        var totGuide=0;
        var valHideIdProd=0;
		$(document).ready(function() {
            $('#divFechaInicio').datetimepicker({
                format: 'DD/MM/YYYY',
                ignoreReadonly: true,
            });
            $('#divFechatras').datetimepicker({
                format: 'DD/MM/YYYY',
                ignoreReadonly: true
            });
            $('#calendar_lot_from').datetimepicker({
                format: 'DD/MM/YYYY',
                ignoreReadonly: true
            });
            $('#calendar_lot_to').datetimepicker({
                format: 'DD/MM/YYYY',
                ignoreReadonly: true
            });
            document.getElementById("loader").style.display = "none";
            $( "#igv" ).val(igv);

            $( "#cliDiv").hide();
            $( "#provDiv").hide();
            $( "#lotDiv").hide();
            $( "#serialDiv").hide();
            if(guide_type == "S"){
                $( "#counterDiv").show();
            }else{
                $( "#counterDiv").hide();
            }
            $("#myModal").on("hidden.bs.modal", function () {
                clearVar();
            });
            $('#myModal').on('shown.bs.modal', function () {
            });
            // capturo valor cantidad de Productos 
            $("#price").blur(function(){
                calcTotProduct();
            });
            $("#avgdiscount").blur(function(){
                calcTotProduct();
            });
            // Evaluo fechas de lote
            $("#production_date").blur(function(){
                var prdDate=$("#production_date").val();
                prdDate = prdDate.split('/').reverse().join('/');
                prdDate=new Date(prdDate);
                // prdDate=new Date(prdDate).toLocaleDateString();
                var expDate=$("#expiration_date").val();
                expDate = expDate.split('/').reverse().join('/');
                expDate=new Date(expDate);
                if(expDate.getFullYear() > 0){
                    if(expDate < prdDate){
                        alert("La fecha de elaboración  no puede ser mayor a la de vencimiento");
                        $("#expiration_date").val('');
                    }
                }    
            });
            $("#expiration_date").blur(function(){
                var prdDate=$("#production_date").val();
                prdDate = prdDate.split('/').reverse().join('/');
                prdDate=new Date(prdDate);
                // prdDate=new Date(prdDate).toLocaleDateString();
                var expDate=$("#expiration_date").val();
                expDate = expDate.split('/').reverse().join('/');
                expDate=new Date(expDate);
                if(prdDate.getFullYear() > 0){
                    if(expDate < prdDate){
                        alert("La fecha de elaboración  no puede ser mayor a la de vencimiento");
                        $("#expiration_date").val('');
                    }
                }
            });

            $("#quantity").blur(function(){
                var serial_number = $( "#serial_number" ).val();
                var exist = series.find(existSerial);
                var cantSeries=series.length;
                quantity=$( "#quantity" ).val();
                if((cantSeries >= quantity)){
                    alert('Las series cargadas superan la cantidad de productos');
                    $( "#quantity" ).val(cantSeries);
                }
                calcTotProduct();
            });
            armoTabla();
            evaluateSuppCus();
            //Evaluo si tengo fecha en edit
            var dateinput ='<?php echo $date; ?>';
            var datetras ='<?php echo $date_tras; ?>';

            if(dateinput != ''){
                $('#dateinput').val(dateinput);
			    $('#fechatras').val(datetras);
            }else{
                //obteniendo fecha actual
                var fActual = new Date().toISOString().split('T')[0];
                //obtneieendo fecha con 30 dias antes de la fecha actual
                var fInicio = new Date().toISOString().split('T')[0];
                //pasando los valores a los filtros de fecha
                // $('#dateinput').val(fInicio.split("-").reverse().join("/"));
                $('#dateinput').val();
                $('#fechatras').val();
                // $('#fechatras').val(fActual.split("-").reverse().join("/"));
            }
			
			 //Llenado el datatable
			dibujarDt("", 1, fInicio, fActual);
			function dibujarDt(paid_status, status_invoice, fecha_inicio, fecha_fin) {
                $('#serieslist').DataTable({
                    'bProcessing': true, 'bServerSide': true,
                    "responsive": true,
                    "order": [[ 2, "desc" ]],
                    "processing": true,
                    "serverSide": true,
                    "ajax": {
                        "url": urlSerie+document_type_id,
                    },
                    "columns": [
                        { "data": "id",
                            className: "text-center" },
                        { "data": "serie" },
                        { "data": "correlative" },
                        { "data": "description" },
                        { "data": "option",
                            className: "text-center" }
                    ],
                    columnDefs: [
                        { orderable: false, targets: -1 },
                        { orderable: false, targets: -2 }
                    ]                
                });
			};
            $( "#addPrdNew" ).click(function() {
                // $("#btn_send_form").show();
                // $("#btn_send_form_update").hide();
            });

            $( "#btnAddSerial" ).click(function() {
                var serial_number = $( "#serial_number" ).val();
                var exist = series.find(existSerial);
                var cantSeries=series.length;
                quantity=$( "#quantity" ).val();
                if((cantSeries >= quantity)){

                    alert("La cantidad de números de series cargados no puede superar a la cantidad declarada de producto."+cantSeries+"/"+quantity);
                }
                else{
                    if(exist == undefined){
                        series.push(serial_number);
                    }else{
                        alert("El producto con serie "+serial_number+" ya se ecuentra cargado")
                    }
                }
                var armoSeries='';
                series.forEach( function(valor, indice, array) {
                    armoSeries+='<button type="button" class="btn btn-secondary"  onclick="borroSerie('+valor+')">'+valor+'</button><br>';
                    //armoSeries+="<a class='btn btn-secondary' onclick='borroSerie("+valor+")' >" + valor +"</a><br>";
                });
                document.getElementById("col_seriales").innerHTML=armoSeries;
                // document.getElementById("col_seriales").innerHTML=series;
            });

            $("#myModal").on("hidden.bs.modal", function () {
                price = 0;
                avgdiscount = 0;
                total=0;
                quantity=0;
                series=[];
                $( "#price" ).val(0);
                $( "#avgdiscount" ).val(0);
                $( "#total" ).val(0);
                $( "#quantity" ).val(0);
                $("#production_date").val('');
                $("#expiration_date").val('');
                $("#lot_number").val('');
                $("#serial_number").val('');
                $("#productSelect").val(0);
                $("#price_inc").val(0);
                $("#idReg").val('');
                document.getElementById("col_seriales").innerHTML="";
                $( "#lotDiv").hide();
                $( "#serialDiv").hide();
            });

            $( "#btn_send_form" ).click(function() {
                var product_id = $( "#productSelect" ).val();
                var lote= $("#lot_number").val();
                var production_date = $("#production_date").val();
                var expiration_date = $("#expiration_date").val();
                var price_inc = $( "#price_inc" ).val();
                var observation_reg = $( "#observation_reg" ).val();
                var evaluate='';
                if(valHideIdProd != product_id){
                    var evaluate = evaluateProductExist();
                }
                if(evaluate=='existe'){
                    return;
                }else{
                    price=$("#price").val();
                    name=$("#name").val();
                    avgdiscount=$("#avgdiscount").val();
                    total=$("#total").val();
                    quantity=$("#quantity").val();
                
                    var cantReg = series.length;
                    if((cantReg < quantity) && (haySerie == 1)){
                        alert('Los números de serie ingresados son inferior a la cantidad de productos declarada');
                        return;
                    }
                    if(product_id == 0 || product_id===null){
                        alert('Debe ingresar un producto');
                        return;
                    }
                    if((hayLote == 1 && ($("#production_date").val()=="" || $("#expiration_date").val()==""))){
                        alert('Verificar fecha de Lote');
                        return;
                    }
                
                    idReg=$("#idReg").val();
                
                    if(idReg != ''){
                        //actualizo  registro
                        var i = dataCol.length;
                        var product = $( "#productSelect" ).val();
                        if (i) {   // (not 0)
                            var y=i;
                            for (let x = 0; x < y; x++)
                            {
                                //resto uno a i para que se adapte al numero de indice del array
                                var cur = dataCol[--i];
                                if (cur.product_id == product) {
                                    
                                    cur.product_id=product_id;
                                    cur.warehouseguide_id=warehouseguide_id,
                                    cur.userguide_id=userguide_id,
                                    cur.local_id=local_id,
                                    cur.lote=lote;
                                    cur.production_date=production_date;
                                    cur.expiration_date=expiration_date;
                                    cur.price=price;
                                    cur.name=name;
                                    cur.price_inc=price_inc;
                                    cur.avgdiscount=avgdiscount;
                                    cur.total=total;
                                    cur.quantity=quantity;
                                    cur.series=series;
                                    cur.observation=observation_reg;
                                    // functionAjax(cur.id, 'update',cur);
                                }
                            }
                        }
                        //fin borro
                        // delete dataCol[idReg];
                        $("#idReg").val('');
                    }else{
                        var exist = dataCol.find(existProduct);
                        if(exist != undefined){
                            alert('El producto ya se encuentra cargado en la guía');
                            return;
                        }
                        var data1={
                            warehouseguide_id:warehouseguide_id,
                            userguide_id:userguide_id,
                            local_id:local_id,
                            product_id:product_id,
                            lote:lote,
                            production_date:production_date,
                            expiration_date:expiration_date,
                            price:price,
                            name:name,
                            price_inc:price_inc,
                            avgdiscount:avgdiscount,
                            total:total,
                            quantity:quantity,
                            series:series,
                            observation:observation_reg
                        };
                    dataCol.push(data1);
                    //functionAjax('','create',data1);
                    // $('#listados').data.reload();
                    }
                    $('#listados').DataTable().destroy();
                    armoTabla();
                    clearVar();
                    calcResume();   
                }   
            });

            function existSerial(nserial) {
                var serial_number = $( "#serial_number" ).val();
                return nserial === serial_number;
            }

            $( "#warehouse_id" ).change(function() {
                var warehouse_name = $("#warehouse_id option:selected" ).text();
                $("#warehouse_name").val(warehouse_name);
            });
            $( "#prov_cli" ).change(function() {
                $('#save_guide').prop('disabled', false);
                $('#update').prop('disabled', false);
                $('#save_guide').removeClass('disabled');
                $('#update').removeClass('disabled');
                var select = $( "#prov_cli" ).val();
                $("#select_prov" ).val("");
                $("#select_cli" ).val("");
                if(select == 1){
                    $( "#cliDiv").hide();
                    $( "#provDiv").show();
                }else{
                    $( "#provDiv").hide();
                    $( "#cliDiv").show();
                }
            });
            
            $( "#select_cli" ).change(function() {
                $('#save_guide').prop('disabled', false);
                $('#update').prop('disabled', false);
                $('#save_guide').removeClass('disabled');
                $('#update').removeClass('disabled');
            });
            $( "#select_prov" ).change(function() {
                $('#save_guide').prop('disabled', false);
                $('#update').prop('disabled', false);
                $('#save_guide').removeClass('disabled');
                $('#update').removeClass('disabled');
            });
            $('#dateinput').blur(function(){
                var fechaExchange= $('#dateinput').val();
                var url = "<?php echo base_url('guides/get_exchange');  ?>";
                $.ajax({
                    type: "get",
                    url: url,
                    data:  {
                        '<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',
                        'data2':fechaExchange
                    },
                    success: function(res) {
                        res=JSON.parse(res);
                        if(res.status=="failed"){
                            return;
                        }else{
                            var curren =res['currency'];
                            $('#exchange').val(res['sell']);
                            $('#currency').val(curren);
                        }
                    }
                });
            });

            $( "#productSelect" ).change(function() {
                $( "#lotDiv").hide();
                $( "#serialDiv").hide();
                document.getElementById("loader").style.display = "block";
                haySerie = 0;
                hayLote = 0;
                
                //Evaluar funcionamiento de repetido;
                var product_id = $( "#productSelect" ).val();
                //evaluateProductExist();
                var url = "<?php echo base_url('guides/get_product');  ?>"+"/"+product_id;
                $.ajax({
                type: "get",
                url: url,
                dataType: "json",
                success: function (data) {
                        document.getElementById("loader").style.display = "none";
                        if (data !== null) {
                            $('#name').val(data['name']);
                            haySerie=data['requires_serial_number'];
                            //Cambiar 1 tiene serie, 0 no
                            if(haySerie==1){
                                // Mostrar combo llenar serie
                                $( "#serialDiv").show();
                            }
                            hayLote=data['requires_lot_number'];
                            if(hayLote==1){
                                // Mostrar combo lote
                                $( "#lotDiv").show();
                            }
                        } else {
                            alert('Error');
                        }
                        document.getElementById("loader").style.display = "none";
                    }
                })
            });
            calcResume();       

		});
        function calcResume(){
            cantElementos = 0;
            totGuide = 0;
            var cantCol = dataCol.length;
            for(var i = 0; i < cantCol; i++){
                var cantI = parseFloat(dataCol[i].quantity);
                var cantT = parseFloat(dataCol[i].total);
                cantElementos += cantI;
                totGuide += cantT;
            };  
            totGuide=totGuide.toFixed(2);
            $( "#itemResume" ).val(cantCol);
            $( "#cantTotResume" ).val(cantElementos);
            $( "#totResume" ).val(totGuide); 
        }   
        function calcTotProduct(){
            price = $( "#price" ).val();
            quantity = $( "#quantity" ).val();
            avgdiscount = $( "#avgdiscount" ).val();
             
            if(is_numeric(price) && is_numeric(quantity) && is_numeric(avgdiscount)){  
                var priceavgdiscount = (100-avgdiscount)/100;
                price=price*priceavgdiscount;
                var subtotal=price*quantity;
                total=((subtotal*(parseFloat(igv)+100))/100);
                total=total.toFixed(2);
                $( "#total" ).val(total);
                var price_inc = ((price*(parseFloat(igv)+100))/100);
                price_inc=price_inc.toFixed(2);
                $( "#price_inc" ).val(price_inc);

            }
        }
        function borroReg(idRegFunction){
            var confirma = confirm('Desea borrar el Registro: '+idRegFunction);
            if(confirma == true){
                var table = $('#listados').DataTable();
                //borro registro
                var i = dataCol.length;
                if (i) {   // (not 0)
                    while (i) {
                        --i;
                        var cur = dataCol[i];
                        if (cur.product_id == idRegFunction) {
                            dataCol.splice(i, 1);
                            var rawencode = JSON.stringify(cur);
                            //functionAjax(cur.id,'delete',rawencode);
                            $('#listados').DataTable().destroy();
                            armoTabla();
                        }
                    }
                }
            }else{

            }
            calcResume();
        }
        function functionAjax(register_id, condition, reg){
            var url='';
            if(warehouseguide_id == ""){
                return;
            }else{
                switch (condition) {
                case 'delete':
                    url = "<?php echo base_url('guides/deleteReg'); ?>"+"/"+register_id;
                    break;
                case 'update':
                    url = "<?php echo base_url('guides/updateReg'); ?>"+"/"+register_id;
                    break;
                case 'create':
                    url = "<?php echo base_url('guides/createReg'); ?>";
                    break;
                default:
                    break;
                }
                document.getElementById("loader").style.display = "block";
                var dataReg = reg;
                // dataReg = JSON.parse(dataReg);
                $.ajax({
                    url: url,
                    type: "GET",
                    data:dataReg,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                    })
                .done(function(data){
                    document.getElementById("loader").style.display = "none";
                })
                .fail(function(xhr, textStatus, errorThrown){
                    console.log("ERROR");
                    document.getElementById("loader").style.display = "none";
                });
            }
        }
        function armoTabla(){
            $.fn.dataTable.ext.errMode = 'throw';
            $('#listados').DataTable({
                "responsive": true,
                "language": {
                    "url": "<?= $assets ?>/dist/js/pages/es_es.lang"
                },
                "displayLength": 25,
                "data":dataCol,
                "columns": [
                    { "title":"#", "data": "product_id" ,  className: "text-center"},
                    { "title":"Nombre", "data": "name", "width": "30%"  },
                    { "title":"Lote", "data": "lote" },
                    { "title":"Elaboracion", "data": "production_date"},
                    { "title":"Vencimiento", "data": "expiration_date" },
                    { "title":"Precio", "data": "price", className: "text-center" },
                    { "title":"Descuento", "data": "avgdiscount", className: "text-center" },
                    { "title":"Cant.", "data": "quantity",  className: "text-center" },
                    { "title":"Total", "data": "total",  className: "text-center" },
                    { "title":"Opciones", "data": null,
                        render: function ( data, type, row ) {
                        return "<a onclick='borroReg("+row.product_id+")' class='tip btn btn-danger btn-xs'><i class='fa fa-trash-o'></i></a>&nbsp;<a onclick='editReg("+row.product_id+")' class='btn-edit tip btn btn-warning btn-xs'><i class='fa fa-edit'></i></a>";   
                        }
                    },
                ]                        
            });
        }
        function clearVar(){
            price = 0;
            name='';
            avgdiscount = 0;
            total=0;
            quantity=0;
            series=[];
            $( "#price" ).val(0);
            $( "#name" ).val('');
            $( "#name" ).val('');
            $( "#avgdiscount" ).val(0);
            $( "#total" ).val(0);
            $( "#quantity" ).val(0);
            $("#production_date").val('');
            $("#expiration_date").val('');
            $("#lot_number").val('');
            $("#serial_number").val('');
            $("#productSelect").val(0);
            $("#observation_reg").val('');
            $( "#price_inc" ).val('');
            document.getElementById("col_seriales").innerHTML="";
            $( "#lotDiv").hide();
            $( "#serialDiv").hide();
            haySerie = 0;
            hayLote = 0;
            valHideIdProd=0;
        }
        function editReg(idReg){
            $("#myModal").modal("show");
            //borro registro
            var i = dataCol.length;
            if (i) {   // (not 0)
                while (i) {
                    --i;
                    var cur = dataCol[i];
                    if (cur.product_id == idReg) {
                        valHideIdProd=idReg;
                        //Armo valores en modal
                        $( "#productSelect" ).val(cur.product_id).change();
                        var productSelect = $("#productSelect option:selected" ).text();
                        // $("#productSelect option[value='"+ cur.product_id+"']").attr("selected","selected");
                        
                        if(cur.lote != undefined && cur.lote != null && cur.lote != ""){
                            $("#lotDiv").show();
                            $("#lot_number").val(cur.lote);
                            $("#production_date").val(cur.production_date);
                            $("#expiration_date").val(cur.expiration_date);
                        }
                        var cantReg = cur.series.length;
                        if(cantReg > 0){
                             $( "#serialDiv").show();
                            series= cur.series;
                            var armoSeries='';
                            series.forEach( function(valor, indice, array) {
                                armoSeries+='<button type="button" class="btn btn-secondary"  onclick="borroSerie('+valor+')">'+valor+'</button><br>';
                                //armoSeries+="<a class='btn btn-secondary' onclick='borroSerie("+valor+")' >" + valor +"</a><br>";
                            });
                            document.getElementById("col_seriales").innerHTML=armoSeries;
                        }
                        $("#price").val(cur.price);
                        $("#name").val(cur.name);
                        $("#serieSelect option[value=1]").html(cur.name);
                        $("#avgdiscount").val(cur.avgdiscount);
                        $("#total").val(cur.total);
                        $("#quantity").val(cur.quantity);
                        $("#observation_reg").val(cur.observation);
                        $("#price_inc").val(cur.price_inc);
                        $("#idReg").val(idReg);
                        // $("#btn_send_form").hide();
                        // $("#btn_send_form_update").show();
                        //Fin armar modal valores 
                    }
                }
                
            }
            //fin borro
        }
        
        function borroSerie(idSerie){
            var i = series.length;
            if (i) {   // (not 0)
                while (i) {
                    --i;
                    var cur = series[i];
                    
                    if (cur == idSerie) {
                        series.splice(i,1);
                        alert('borro Serie: '+idSerie);
                       
                    }
                }
                var armoSeries='';
                series.forEach( function(valor, indice, array) {
                    armoSeries+='<button type="button" class="btn btn-secondary"  onclick="borroSerie('+valor+')">'+valor+'</button><br>';
                    //armoSeries+="<a class='btn btn-secondary' onclick='borroSerie("+valor+")' >" + valor +"</a><br>";
                });
                document.getElementById("col_seriales").innerHTML=armoSeries;
            }
        };
        function evaluateSuppCus(){
            if(prov_cli == 1){
                $( "#cliDiv").hide();
                $( "#provDiv").show();
            }else if(prov_cli == 2){
                $( "#provDiv").hide();
                $( "#cliDiv").show();
            }else{
                $( "#provDiv").hide();
                $( "#cliDiv").hide();
            }
        };
        function existProduct(product_id) { 
            var productid = $( "#productSelect" ).val();
            return product_id.product_id === productid;
        }
        function evaluateProductExist(){
             //Evaluar funcionamiento de repetido;
            var product_id = $( "#productSelect" ).val();
            var exist=[];
            dataCol.forEach( function(valor, indice, array) {
                var undi=dataCol.find(existProduct);
                if( undi !==undefined){
                    exist.push(dataCol.find(existProduct));
                }
            });
            
            if(exist.length > 1){
                alert('El producto ya se encuentra cargado en la guía');
                $( "#productSelect" ).val(null);
                document.getElementById("loader").style.display = "none";
                return 'existe';
            }
        }
        $( "#formGuide" ).submit(function(e) {
            var customer_name = $("#select_cli option:selected" ).text();
            var customer_val = $("#select_cli" ).val();
            var supplier_name = $("#select_prov option:selected" ).text();
            var supplier_val = $("#select_prov" ).val();
            var supplier_val = $("#select_prov" ).val();
            var date1 = $('#dateinput').val();
            if(customer_val == ""){
                $("#customer_name").val(null);
            }else{
                $("#customer_name").val(customer_name);
            }
            if(supplier_val == ""){
                $("#supplier_name").val(null);
            }else{
                $("#supplier_name").val(supplier_name);
            }

            if(date1 == ""){
                alert('Seleccione una fecha para la guía');
                e.preventDefault();
            }
            var myJSON = JSON.stringify(dataCol);
            $("#warehouseguide_detail").val(myJSON);
            if(customer_val == "" && supplier_val == "" ){
                alert('Seleccione un cliente o proveedor');
                return false;
                // e.preventDefault();
            }
        });
        
	</script>
</section>
<script>

</script>
<style>
    .selectProvCli { 
        width: 250px !important;
    }
    #loader {
        background-color: rgba(0,0,0,0.3);
        position: absolute;
        left: 50%;
        top: 50%;
        z-index: 99;
        width: 120px;
        height: 120px;
        margin: -76px 0 0 -76px;
        border: 16px solid #f3f3f3;
        border-radius: 50%;
        border-top: 16px solid #3498db;
        -webkit-animation: spin 2s linear infinite;
        animation: spin 2s linear infinite;
    }
    div.col_seriales {
        background-color: #E9E9E9;
        height: 200px;
        width: 200px;
        overflow-y: scroll;
        }
</style>