
<div id="estiba">
    <div class="row mt-2 mb-3">
        <div class="col-sm">
            <button type="button" class="btn btn-primary ml-2" onclick="nuevo_estiba();">Nuevo</button>
            <!-- <button type="button" class="btn btn-primary ml-2" data-toggle="modal" data-target="#modalForm" onclick="editar_estiba();">Editar</button> -->
            <button type="button" class="btn btn-secondary ml-2" onclick="actualizar_pagina();">Atualizar Tabla</button>
            <button type="button" class="btn btn-success ml-2" onclick="formulario_estiba();">Tiempo Real</button>
        </div>
    </div>

    <table id="table_estiba" class="display" style="width: 100%">
        <thead>
            <tr>
                <th hidden="hidden">ID</th>
                <th>Orden</th>
                <th>Pallet</th>
                <th>T° Min</th>
                <th>T° Max</th>
                <th>Termógrafo</th>
                <th>Sentido</th>
                <th>Cumple</th>
                <th>Sincro</th>
                <th>Eliminar</th>
            </tr>
        </thead>
        <tbody>
            <?php
            if (isset($_REQUEST['folio_planillavuelta'])) {
                $folio_planilla = $_REQUEST['folio_planillavuelta'];
                include '../../conexion/session.php';
                include '../../conexion/conn.php';
            }
            date_default_timezone_set('America/Santiago');
            $fecha_actual = date("Y-m-d");
            $rs = mysql_query("SELECT * FROM contenedor_estiba WHERE folio_planilla = '$folio_planilla'");

            while ($row = mysql_fetch_array($rs)) {
            ?>
                <tr>
                    <td hidden="hidden"><?php echo $row['id_estiba']; ?></td>
                    <td><?php echo $row['orden_pallet']; ?></td>
                    <td><?php echo $row['folio_pallet']; ?></td>
                    <td><?php echo $row['temp_min']; ?></td>
                    <td><?php echo $row['temp_max']; ?></td>
                    <td><?php echo $row['num_termo']; ?></td>
                    <td><?php echo $row['sentido_pallet']; ?></td>
                    <td><?php echo $row['cumple_norma']; ?></td>
                    <td><?php echo $row['sincro']; ?></td>
                    <td><button type="button" class="btn btn-danger" onclick="eliminar_estiba(<?php echo $row['id_estiba']; ?>);">Eliminar</button></td>
                </tr>
            <?php
            }
            ?>
        </tbody>
    </table>


    <!-- Modal  NUEVO-->
    <div class="modal fade" id="modalForm" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" width="100%">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLongTitle">Form</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <!-- Stack the columns on mobile by making one full-width and the other half-width -->
                        <div class="jumbotron" style="padding: 5px; height: 10%; margin: 0px;">
                            <div class="row" style="display:flex; justify-content:center; align-items:center; flex-wrap:wrap; gap: 12px; ">
                                <div class="col-sm" style="min-width:200px">
                                    <label for="c">Orden</label>
                                    <input class="form-control" id="orden_pallet" name="orden_pallet" type="number" />
                                </div>
                                <div class="col-sm" style="min-width:200px">
                                    <label for="c">Folio Pallet</label>
                                    <input type="text" class="form-control" id="folio_pallet" name="folio_pallet" />
                                </div>
                                <div class="col-sm" style="min-width:200px">
                                    <label for="c">Temp 1 (C°)</label>
                                    <input class="form-control" id="temp_min" name="temp_min" type="number">
                                </div>
                                <div class="col-sm" style="min-width:200px">
                                    <label for="c">Temp 2 (C°)</label>
                                    <input class="form-control" id="temp_max" name="temp_max" type="number">
                                </div>
                                <div class="col-sm" style="min-width:300px">
                                    <label for="c">Termografo</label>
                                    <select class="form-control" id="num_termo" name="num_termo">
                                        <?php
                                        $rs = mysql_query("SELECT termografo_1, termografo_2 FROM contenedor_planilla WHERE folio_planilla = '$folio_planilla'");
                                        if ($row = mysql_fetch_array($rs)) {
                                        ?>
                                            <option value="">Seleccione si hay ...</option>
                                            <option value="<?php echo $row['termografo_1']; ?>">Termografo 1 - <?php echo $row['termografo_1']; ?></option>
                                            <option value="<?php echo $row['termografo_2']; ?>">Termografo 2 - <?php echo $row['termografo_2']; ?></option>
                                        <?php
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="row" style="display:flex; justify-content:center; align-items:center;">

                                    <div class="col-sm" style="min-width:200px; display:flex; justify-content:center; align-items:center; flex-direction: column">
                                        <label for="c">Sentido</label>
                                        <div class="o-switch btn-group" data-toggle="buttons" role="group">
                                            <label class="btn btn-secondary active">
                                                <input type="radio" name="check_sentido" id="check_sentidop" value="P" autocomplete="off" checked> P
                                            </label>
                                            <label class="btn btn-secondary">
                                                <input type="radio" name="check_sentido" id="check_sentidoe" value="E" autocomplete="off"> E
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
                    <button type="button" class="btn btn-primary" onclick="guardar_estiba();">Guardar</button>
                </div>
            </div>
        </div>
    </div>

</div>

<!-- Bootstrap core JavaScript
    ================================================== -->
<script type="text/javascript">
    var events;
    var table;
    var rowData;
    var arreglo = "";
    $(document).ready(function() {
        // Setup - add a text input to each footer cell
        $('#table_estiba thead tr').clone(true).appendTo('#table_estiba thead');
        $('#table_estiba thead tr:eq(1) th').each(function(i) {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="Search ' + title + '" style="width:70px;" />');

            $('input', this).on('keyup change', function() {
                if (table.column(i).search() !== this.value) {
                    table
                        .column(i)
                        .search(this.value)
                        .draw();
                }
            });
        });

        var table = $('#table_estiba').DataTable({
            orderCellsTop: true,
            fixedHeader: true,
            select: true,
            "pageLength": 25,


        });

        table
            .on('select', function(e, dt, type, indexes) {
                var rowData = table.rows(indexes).data().toArray();
                //events.prepend( '<div><b>'+type+' selection</b> - '+JSON.stringify( rowData )+'</div>' ); listar fila
                arreglo = rowData;
                $('#modalForm').modal('toggle');
                editar_estiba();

            })
            .on('deselect', function(e, dt, type, indexes) {
                var rowData = table.rows(indexes).data().toArray();
                //events.prepend( '<div><b>'+type+' <i>de</i>selection</b> - '+JSON.stringify( rowData )+'</div>' ); listar fila
                arreglo = "";
            });

    });

    var url;

    function nuevo_estiba() {
        var folio_planilla = <?php echo json_encode($folio_planilla); ?>;
        url = 'Ingreso/Planillas/save_estiba.php?folio_planilla=' + folio_planilla;
        guardar_estiba();
    }

    function editar_estiba() {
        if (arreglo != "") {
            $('#orden_pallet').val(arreglo[0][1]);
            $('#folio_pallet').val(arreglo[0][2]);
            $('#temp_min').val(arreglo[0][3]);
            $('#temp_max').val(arreglo[0][4]);
            $('#num_termo').val(arreglo[0][5]);
            $('input:radio[name=check_sentido]:checked').val(arreglo[0][6]);
            if (arreglo[0][6] == "P") {
                $('#check_sentidop').prop('checked', true);
            } else if (arreglo[0][6] == "E") {
                $('#check_sentidoe').prop('checked', true);
            }

            url = 'Ingreso/Planillas/update_pallet.php?id_estiba=' + arreglo[0][0] + '&sincro=' + arreglo[0][8];
        } else {
            alert("Seleccione un Registro");
            location.reload();
        }
    }

    function guardar_estiba() {
        var orden_pallet = $('#orden_pallet').val();
        var folio_pallet = $('#folio_pallet').val();
        var temp_min = $('#temp_min').val();
        var temp_max = $('#temp_max').val();
        var num_termo = $('#num_termo').val();
        if ($('#check_sentidop').is(':checked')) {
            var sentido_pallet = "P";
        } else if ($('#check_sentidoe').is(':checked')) {
            var sentido_pallet = "E";
        }

        var folio_planilla = <?php echo json_encode($folio_planilla); ?>;

        $.ajax({
            type: 'POST',
            url: url,
            data: {
                "orden_pallet": orden_pallet,
                "folio_pallet": folio_pallet,
                "temp_min": temp_min,
                "temp_max": temp_max,
                "num_termo": num_termo,
                "sentido_pallet": sentido_pallet
            },
            dataType: 'json',
            cache: false,
            success: function(result) {
                if (result.success) {
                    $('#modalForm').modal('toggle');
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove();
                    // window.location.href = 'inspector.php?inspeccion=ingresocont&folio_planilla='+folio_planilla+'&estiba=1';
                    // $('#estiba').load("Ingreso/Planillas/pallet.php?folio_planillavuelta=" + folio_planilla);
                    window.location.href = 'inspector.php?inspeccion=ingresocont&folio_planilla='+folio_planilla+'&estiba=1';
                    //location.reload();
                    if (result.result) {
                        alert("Registro Guardado");
                        
                    }
                } else {
                    alert("Error al registrar, verifique la informacion.");
                }

            },
        });

    }

    function formulario_estiba() {
        var folio_planilla = <?php echo json_encode($folio_planilla); ?>;
        $('#estiba').load("Ingreso/Planillas/formulario.php?folio_planilla=" + folio_planilla);
    }

    function actualizar_pagina() {
        var folio_planilla = <?php echo json_encode($folio_planilla); ?>;
        $('#estiba').load("Ingreso/Planillas/pallet.php?folio_planillavuelta=" + folio_planilla);
    }

    function eliminar_estiba(id_estiba) {
        var folio_planilla = <?php echo json_encode($folio_planilla); ?>;
        if (confirm("Desea Borrar la Estiba " + id_estiba + "?")) {
            $.ajax({
                type: 'POST',
                url: 'Ingreso/Planillas/eliminar_estiba.php',
                data: {
                    "id_estiba": id_estiba,
                    "folio_planilla": folio_planilla
                },
                dataType: 'json',
                cache: false,
                success: function(result) {

                    if (result.success) {
                        alert("eliminado");
                        $('body').removeClass('modal-open');
                        $('.modal-backdrop').remove();
                        $('#estiba').load("Ingreso/Planillas/pallet.php?folio_planillavuelta=" + folio_planilla);
                    } else {
                        alert("Error al registrar, verifique la informacion.");
                    }

                },
            });
        }
    }
</script>