<?php (defined('BASEPATH')) OR exit('No direct script access allowed'); ?>
<?php
    if($idDoc==null){
        $idDoc='';
    }
?>
<script>
    var document_type_id = '<?php echo ($idDoc) ?>';
    var urlSerie = "<?= site_url('series/get') ?>"+'/';
</script>

<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
                <div class="panel panel-default">
                    <div class="panel-heading" role="tab" id="headingOne">
                        <h4 class="panel-title">
                            <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                <strong><?= lang('filter'); ?></strong>
                            </a>
                        </h4>
                    </div>
                    <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
                        <div class="panel-body">
                            <div class="col-lg-12">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <?= "<label>Tipo de documento</label>"; ?>
                                            <?php
                                            $sw=[];
                                            $html_select = '<select class="form-control select2 serieSelect" id="serieSelect"  required="required" style="width:100%;">';
                                            if($documents != null){
                                                foreach($documents as $doc) {
                                                    //$sw[$doc['id']] = $doc['code'].'-'.$doc['description'];
                                                    $sw[$doc['id']] = $doc['description'];
                                                    $html_select = $html_select . '<option value="'.$doc['id'].'" data-codedocsunat="'.$doc['code'].'" >'.$doc['description'].'</option>';
                                                }
                                            }
                                            $html_select = $html_select . '</select>';
                                            ?>
                                            <?= $html_select; ?>
                                        </div>
                                    </div>
                                    <div class="col-md-6 botones">
                                        <div class="form-group">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
    <div class="col-md-12">
    <div>
    <?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.'</il>';
                        }
                    }
                    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>';
                }  
            }
        };
        */
    ?>
        </div>
            <div class="form-group">
                <a href="#" class="btn btn-primary btn-edit" data-toggle="modal" data-target="#myModal" data-id="0" > Nuevo</a>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="box" style="border-top: 2.5px solid #004785;">
                <!--div class="box-header">
                    <h3 class="box-title"><?= lang('list_results'); ?></h3>
                </div-->
                <div class="box-body">
                <div class="table-responsive">
                    <table id="serieslist" class="table table-striped table-bordered table-condensed table-hover" style="width:100%">
                        <thead class="text-center">
                            <tr>
                                <th class="col-sm-1" class="text-center"><?= lang("code_doc_sunat"); ?></th>
                                <th class="col-sm-2"><?= lang("Serie"); ?></th>
                                <th class="col-sm-2"><?= lang("correlative2"); ?></th>
                                <th class="col-sm-5"><?= lang("description"); ?></th>
                                <th class="col-sm-1" class="text-center"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="9" class="dataTables_empty"><?= lang('loading_data_from_server') ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
    </div>
    
  <!-- Button trigger modal -->

    <?= form_open( base_url('series/save'), 'id="serie-form"'); ?>
    <!-- Modal -->
    <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>Tipo de documento: <span id="descDoc"></span></h4>
               
            </div>
            <div class="modal-body">
                <input type="hidden" id="idSerie" name="idSerie">
                <input type="hidden" id="document_type_id" name="document_type_id">
                <div class="form-group">
                    <div>
                        <div id="serieIni" style="display: none">
                            <span class="label label-warning">Serie Iniciada</span>
                        </div>
                        <div id="notIni" style="display: none">
                            <span class="label label-info">Serie no iniciada</span>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="serieEdit">Serie</label>
                    <input type="text" class="form-control" id="serieEdit" name="serieEdit" 
                        placeholder="Serie" maxlength="4" pattern="([0-9]{4})" required>
                    <span class="label label-warning" id="serieEditAlert"  >Campo requerido</span>
                </div>
                <div class="form-group">
                    <label for="correlativeEdit">Nro Correlativo</label>
                    <input type="number" class="form-control" id="correlativeEdit" name="correlativeEdit" 
                        placeholder="Nro Correlativo" pattern="/^-?\d+\.?\d*$/" 
                        onKeyPress="if(this.value.length==8) return false;" required>
                    <span class="label label-warning" id="correlativeEditAlert"  >Campo requerido</span>
                </div>
                <div class="form-group">
                    <label for="descriptionEdit">Descripci&oacute;n</label>
                    <textarea class="form-control" id="descriptionEdit" name="descriptionEdit"
                        placeholder="Descripci&oacute;n" maxlength="200" required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="btn_send_form"> <?="<label>Aceptar</label>"?> </button>
                <button type="button" class="btn btn-default" data-dismiss="modal"><?=lang('close')?> </button>
                        
            </div>
            </div>
        </div>
    </div>
    <?= form_close(); ?>
</section>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?= $assets ?>plugins/datatables/datatable.min.js"></script>
<script>
    var idSerie=0;
    var serieEdit= "";
    var correlativeEdit= "";
    var descriptionEdit= "";
    var flg_started= "";
    var descriptionDocu= "";
    var codesunatDocu= "";
    $( document ).ready(function() {
        document.getElementById("loader").style.display = "none";
        document_type_id = $("#serieSelect").val();
        descriptionDocu = $( "#serieSelect option:selected" ).text();
        codesunatDocu = $( "#serieSelect option:selected" ).attr('data-codedocsunat');
        $("#descDoc").text(descriptionDocu);
        $(".modal-body #document_type_id").val( document_type_id );

        $( ".serieSelect" ).change(function() {
            descriptionDocu = $( "#serieSelect option:selected" ).text();
            codesunatDocu = $( "#serieSelect option:selected" ).attr('data-codedocsunat');
            $("#descDoc").text(descriptionDocu);
            document_type_id = $("#serieSelect").val();
            var table = $('#serieslist').DataTable();
            table.destroy();
            createTable();
        });

        $("#serieEditAlert").hide();
        $("#correlativeEditAlert").hide();

        if(document_type_id == null){
            alert('No hay Documentos cargados en el sistema');
        }else{
            createTable();            
        }
    });

    function createTable(){
        $('#serieslist').DataTable({
            'bProcessing': true, 'bServerSide': true,
            "responsive": true,
            "order": [[ 2, "desc" ]],
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": urlSerie+document_type_id,
            },
            "columns": [
                { "data": "",
                    className: "text-center",
                    "render": function ( data, type, row, meta ) {
                        if( row.correlative != "" ){
                            return codesunatDocu;
                        } else {
                            return "";
                        }
                    }
                },
                { "data": "serie" },
                { "data": "correlative" },
                { "data": "description" },
                { "data": "option",
                    className: "text-center" }
            ],
            columnDefs: [
                { orderable: false, targets: -1 },
                { orderable: false, targets: -2 }
            ]                
        });
    }
    
    $(document).on("click", ".btn-edit", function () {
        idSerie = $(this).data('id');
        $(".modal-body #idSerie").val( idSerie );
    });
    $("#btn_send_form").click(
        function(){
            $(".modal-body #document_type_id").val( document_type_id );
            document.getElementById("loader").style.display = "block";
            serieEdit =  $("#serieEdit").val();
            correlativeEdit = $("#correlativeEdit").val();;
            if((serieEdit == '') || (serieEdit == undefined) || (serieEdit== null)){
                $("#serieEditAlert").show();
                $("#correlativeEditAlert").hide();
                document.getElementById("loader").style.display = "none";
                return;
            } else if((correlativeEdit == '') || (correlativeEdit == undefined) || (correlativeEdit== null)){
                $("#correlativeEditAlert").show();
                $("#serieEditAlert").hide();
                document.getElementById("loader").style.display = "none";
                return;
            } else{
                var edit = $(".modal-body #idSerie").val();
                let form = $('#serie-form');
                if(edit!=0){
                    let url = form.attr('action','<?php echo base_url('series/save'); ?>');
                }else{
                    let url = form.attr('action','<?php echo base_url('series/new'); ?>');
                }
                $("#serie-form").submit();
            }
        }
    );
    $("#myModal").on("hidden.bs.modal", function () {
        serieEdit= "";
        correlativeEdit= "";
        descriptionEdit= "";
        document_type_id= "";
        flg_started= "";
        descriptionDocu="";
        $(".modal-body #serieEdit").val( serieEdit );
        $(".modal-body #correlativeEdit").val( correlativeEdit );
        $(".modal-body #descriptionEdit").val( descriptionEdit );
        $(".modal-body #document_type_id").val( document_type_id );
    });
    $('#myModal').on('shown.bs.modal', function () {
        document.getElementById("loader").style.display = "block";
        $(".modal-body #document_type_id").val( document_type_id );
        $( "#notIni" ).hide();
        $( "#serieIni" ).hide();
        $('#myInput').focus();
        var data = "";
        // var edit =document.getElementById(".modal-body #serieEdit").value;
        var edit = $(".modal-body #idSerie").val();

        if(edit > 0){
            $("input").attr('disabled','disabled');
            document.getElementById("loader").style.display = "block";
            $.ajax({
                type: "get",
                url: base_url+'series/show/'+idSerie,
                dataType: "json",
                success: function (data) {

                    if (data !== null) {
                        data = data.data.data;
                        serieEdit= data.serie;
                        correlativeEdit= data.correlative;
                        descriptionEdit= data.description;
                        document_type_id= data.document_type_id;
                        flg_started= data.flg_started;
                        $(".modal-body #serieEdit").val( serieEdit );
                        $(".modal-body #correlativeEdit").val( correlativeEdit );
                        $(".modal-body #descriptionEdit").val( descriptionEdit );
                        $(".modal-body #document_type_id").val( document_type_id );

                        if(flg_started==0){
                            $( "#notIni" ).show();
                        }else{
                            $( "#serieIni" ).show();
                        }
                        document.getElementById("loader").style.display = "none";
                    } else {
                        alert('Error');
                        document.getElementById("loader").style.display = "none";
                    }
                    $("input").removeAttr('disabled');
                }
            })
        }else{
            document.getElementById("loader").style.display = "none";
        }
    });

</script>
<style>
/* Center the loader */
#loader {
  background-color: rgba(0,0,0,0.3);
  position: absolute;
  left: 50%;
  top: 27%;
  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;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}


</style>