<section class="content-header">

    <h1><i class='fa-fw fa fa-certificate'></i> <?php echo $_translator->_getTranslation('Modulo de horneado'); ?></small></h1>

    <ol class="breadcrumb">

        <li><a href="<?php echo ROOT_HOST ?>/Controller/Home.php"><i class="fa fa-dashboard"></i><?php echo $_translator->_getTranslation('Inicio') ?></a></li>


        <li class="active"><?php echo $_translator->_getTranslation('Modulo de Horneado'); ?></li>

    </ol>

</section>

<section class="content">

    <div class="box">

        <?php echo $_form->openForm(); ?>

        <div style="display: none"><?php

                                    echo $_form->showActionController();

                                    echo $_form->showId();

                                    $_form->showElement('status'); ?>

        </div>

        <div class='flashmessenger'><?php $flashmessenger->showMessage(); ?></div>

        <div class="box-header with-border">

        </div><!-- /.box-header -->

        <div class="box-body">

            <div class="card">

                <ul class="nav nav-tabs" role="tablist">

                    <li role="presentation" class="active"><a href="#tab_general" aria-controls="home" role="tab" data-toggle="tab"><?php echo $_translator->_getTranslation('-') ?></a></li>

                    <!--<li role="presentation"><a href="#tab_attachments" aria-controls="profile" role="tab" data-toggle="tab"><?php echo $_translator->_getTranslation('Adjuntos') ?></a></li>          -->

                </ul>

                <!-- Tab panes -->

                <div class="tab-content" style="padding-top: 20px">

                    <div role="tabpanel" class="tab-pane active" id="tab_general">
                        <div class="row">
                            <div class="col-xs-12 col-md-6">
                                <?php echo $_form->showElement('id_sucursal'); ?>
                                <br>
                            </div>
                            <div class="col-xs-12 col-md-6">
                                <label>

                                </label>
                            </div>
                            <br>
                            <div class="col-xs-12 col-md-12 hidden" id="div_horneado">


                                <div class=" invoice-info">
                                    <div class="col-xs-12 col-md-3 invoice-col" style="font-size: 24px;">

                                        Fecha: <strong id="current_date"></strong><br>
                                        <strong id="div_sucursal">Sucursal: <strong id="lbl_sucursal"></strong></strong>
                                    </div>
                                    <!-- /.col -->
                                    <div class="col-xs-12 col-md-3 invoice-col">


                                    </div>
                                    <div class="col-lg-3 col-xs-6">
                                        <!-- small box -->
                                        <div class="small-box bg-aqua">
                                            <div class="inner">
                                                <h3 id="lbl_horneado_pzas">0</h3>

                                                <p>Horneado Pzas</p>
                                            </div>
                                            <div class="icon">
                                                <i class="ion ion-ios-filing-outline"></i>
                                            </div>
                                            <!-- <a href="#" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a> -->
                                        </div>
                                    </div>
                                    <div class="col-lg-3 col-xs-6">
                                        <!-- small box -->
                                        <div class="small-box bg-green">
                                            <div class="inner">
                                                <h3 id="lbl_charolas_qty">0</h3>

                                                <p>Charolas:</p>
                                            </div>
                                            <div class="icon">
                                                <i class="ion ion-ios-filing-outline"></i>
                                            </div>
                                            <!-- <a href="#" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a> -->
                                        </div>
                                    </div>
                                </div>

                            </div>

                            <div class="col-xs-12 col-md-12">
                                <div class="table-responsive">
                                    <table id="Tablabotones" class="table table-bordered text-center">
                                        <tbody>
                                            <?php
                                            //$productos = ["CONCHA", "DANES", "CUERNITO", "CALZON", "CARTERA", "BESO", "BIGOTE", "EMPANADA", "LECHUZA", "MARRANITO", "DANES ALMENDRA"];
                                            $productos = $dataProduct;


                                            $totalProductos = count($productos);


                                            $columns = 4; // Fijar siempre 6 botones por fila
                                            $colWidth = 3; // Columna fija de tamaño col-md-2

                                            $i = 0;


                                            foreach ($productos as $producto) {

                                                $description = htmlspecialchars($producto['description'], ENT_QUOTES, 'UTF-8'); // Escapa valores para evitar problemas de seguridad
                                                $id = htmlspecialchars($producto['id'], ENT_QUOTES, 'UTF-8');
                                                echo "<tr class='product-row'>
                                                        <td>
                                                            <button type='button' id='$id' class='btn btn-default btn-flat product-button' style='width: 100%; height: 100px;' onclick='selectButton(this)'>
                                                                $description
                                                            </button>
                                                        </td>
                                                    </tr>";                                                                                                                                                            
                                            }
                                            ?>
                                        </tbody>
                                    </table>
                                </div>

                            </div>

                            <div class="clear"></div>

                            <div class="col-xs-12 col-md-12">

                                <h4><?php echo $_translator->_getTranslation('Lista de horneado diario'); ?></h4>

                                <hr />

                                <table id="tblBaking" class="table table-striped table-bordered table-condensed table-hover">

                                    <thead>

                                        <tr>

                                            <th class="col-md-1 text-center"><?php echo $_translator->_getTranslation('Accion'); ?></th>

                                            <th class="col-md-2 text-center"><?php echo $_translator->_getTranslation('Producto'); ?></th>

                                            <th class="col-md-2 text-center"><?php echo $_translator->_getTranslation('Charola'); ?></th>


                                            <th class="col-md-2 text-center"><?php echo $_translator->_getTranslation('Piezas'); ?></th>

                                            <th class="col-md-1 text-center"><?php echo $_translator->_getTranslation('Fecha'); ?></th>

                                            <th class="col-md-1 text-center"><?php echo $_translator->_getTranslation('Hora'); ?></th>

                                            <th class="col-md-1 text-center"><?php echo $_translator->_getTranslation('Creado Por'); ?></th>

                                        </tr>

                                    </thead>

                                    <tbody>

                                    </tbody>

                                </table>

                                <br />



                                <div class="clear"></div>

                            </div>

                        </div>

                        <div class='clear'></div>

                        <br /><br /><br />

                        <div class='col-md-6'>


                        </div>

                        <div class='col-md-6'>



                        </div>

                    </div>

                    <div role="tabpanel" class="tab-pane" id="tab_attachments"></div>

                </div>

            </div>

            <div class="clear"></div>

            <br /><br /><br />

            <div class="pull-right">



            </div>

        </div><!-- /.box-body -->

        <?php echo $_form->closeForm(); ?>

    </div><!-- /.box -->

</section>

<style>
    .table-responsive {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
    }

    .table-responsive td,
    .table-responsive th {
        white-space: nowrap;
        /* Evita que el contenido se desborde */
    }

    .table-responsive button {
        flex: 1 1 auto;
        margin: 5px;
        padding: 10px;
        font-size: 14px;
        /* Ajusta el tamaño de la fuente según sea necesario */
        height: auto;
        /* Permite que la altura se ajuste automáticamente */
        width: 100%;
        /* Asegura que el botón ocupe todo el ancho de la celda */
    }

    .number-pad {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
    }

    .number-pad .btn {
        flex: 1 1 30%;
        margin: 5px;
    }

    .number-pad .btn-success {
        flex: 1 1 100%;
        margin-top: 10px;
    }

    .custom-btnTeclado {
        color: black;
        font-weight: bold;
        margin: 5px;
        padding: 10px 20px;
        margin-bottom: 10px;
        width: 80px;
        font-size: 20px;
    }

    .dataTables_empty {

        display: none;

    }



    div.gallery_images .thumbail {

        padding: 8px;

        margin: 5px;

        width: 48%;

        border: 1px solid #ccc;

        text-align: center;

    }



    div.gallery_images .thumbail img {

        max-height: 100%;

        max-width: 100%;

        vertical-align: middle;

    }

    .btn-selected {
        border: 11px solid rgba(0, 0, 255, 0.5);
        /* Azul tenue */
    }
</style>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.0/font/bootstrap-icons.css">
<?php include ROOT . "/View/Modal/addBakingQty.php"; ?>
<script>
    let id_sucursal = 0;
    let fecha_actual = '';
    window.onload = adjustTable;
    window.onresize = adjustTable;
    document.addEventListener("DOMContentLoaded", function () {
    adjustTable();

    const selectSucursal = document.getElementById("id_sucursal");
    if (selectSucursal) {
        selectSucursal.addEventListener("change", function () {
            activeSucursal(this);
        });
    }
});
    $(document).ready(function() {
        

        

        var currentDate = new Date();
        var day = String(currentDate.getDate()).padStart(2, '0');
        var month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Los meses empiezan desde 0
        var year = currentDate.getFullYear();
        var formattedDate = day + '/' + month + '/' + year;
        $('#current_date').text(formattedDate);
        fecha_actual = formattedDate;

        var $selectElement = $('select[name="id_sucursal"]');
        if ($selectElement.length && $selectElement.find('option').length === 2) { // Incluye la opción "Seleccione una sucursal" y una opción válida
            $selectElement.prop('selectedIndex', 1); // Selecciona la única opción válida
            $selectElement.trigger('change'); // Dispara el evento change
        }
        
    });

    function adjustTable() {
    const tableBody = document.getElementById("Tablabotones");
    const buttons = document.querySelectorAll(".product-button");
    const screenWidth = window.innerWidth;

    // Define button width (colWidth) dynamically
    let buttonsPerRow;
    if (screenWidth >= 1200) {
        buttonsPerRow = 6; // Large screens
    } else if (screenWidth >= 992) {
        buttonsPerRow = 4; // Medium screens
    } else if (screenWidth >= 768) {
        buttonsPerRow = 3; // Small screens
    } else {
        buttonsPerRow = 2; // Extra small screens
    }

    tableBody.innerHTML = ""; // Limpia la tabla antes de reconstruirla

    let row;
    buttons.forEach((button, index) => {
        if (index % buttonsPerRow === 0) {
            row = document.createElement("tr");
            tableBody.appendChild(row);
        }

        const cell = document.createElement("td");
        cell.style.width = `${100 / buttonsPerRow}%`;
        cell.appendChild(button);

        // Asegurarse de que los botones empiecen deshabilitados
       
        row.appendChild(cell);
    });
}


    function saveBakingTransaction() {

        var id_producto = $('.btn-primary').attr('id');
        var cantidad = $('#monto').val();
        if (cantidad == '' || cantidad == 0) {
            $('.flashmessenger').html('Debe ingresar una cantidad valida.');
            return;
        }
        id_sucursal = $('#id_sucursal').val();
        if(id_sucursal == 0 || id_sucursal == ''){
            $('.flashmessenger').html('<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button><i class="fa fa-check-circle fa-lg "></i> Debes seleccionar una sucursal</div>');
            return;
        }
        $.post('/Controller/Baking.php', {
            action: 'ajax',
            request: 'saveBakingTransaction',
            id_sucursal: id_sucursal,
            id_producto: id_producto,
            cantidad_charolas: cantidad,
            fecha_actual: fecha_actual
        }, function(data) {

            if (data.response) {
                $('.flashmessenger').html(data.msg);
                $('#modalAddBakingQty').modal('hide');
                $("#monto").val('');
                getInformationBaking();
            } else {
                $('.flashmessenger').html(data.msg);
            }
        }, 'json');
    }
    $('._closeModalBaking').on('click', function() {

        $('.flashmessenger').html('');
        $('#modalAddBakingQty').modal('hide');
        $('.btn').removeClass('btn-primary');

    });

    $('.sparko_billetes .btn_numPad').on('click', function() {
        setPaymentAmount(this);
    });
    $('#modalAddBakingQty').on('shown.bs.modal', function(e) {

    });

    function setPaymentAmount(btn) {

        var value = $(btn).data("value");

        if (value === "clear") {

            $("#monto").val("");

            return true;

        } else if (value === "backspace") {

            var amount = $("#monto").val();

            amount = amount.slice(0, -1);

            $("#monto").val(amount);

            return true;

        } else if (value === "cancel") {

            clearPaymentForm();

            disabledAddPayment();

            return true;

        } else if (value === "done") {

            return saveBakingTransaction();

        } else if (btn.classList.contains("quickPaymentBtn")) {

            $("#monto").val();

            $("#monto").val(value);

            $('[data-value="done"]').trigger("click");

            return true;

        }

        var amount = $("#monto").val();

        amount = amount.toString() + value;

        var preg = /^([0-9]+\.?[0-9]{0,2})$/;


        if (preg.test(amount) === true) {

            $("#monto").val(amount);

        } else {

            return false;

        }

    }

    function selectButton(button) {

        // Remover la clase de todos los botones
        $('.btn').removeClass('btn-primary');
        // Agregar la clase al botón seleccionado
        $(button).addClass('btn-primary');
        id_sucursal = $('#id_sucursal').val();
        if(id_sucursal == 0 || id_sucursal == ''){
        
            $('.flashmessenger').html('<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button><i class="fa fa-check-circle fa-lg "></i> Debes seleccionar una sucursal</div>');
            return;
        }
        $('#modalAddBakingQty').modal('show');
    }

    function activeSucursal(e) {
    const selectedValue = e.value;

    if (selectedValue && selectedValue !== "") {
        const selectedText = e.options[e.selectedIndex].innerHTML;

        // Actualiza información visual
        id_sucursal = selectedValue;
        $('#lbl_sucursal').text(selectedText);
        $('#div_horneado').removeClass('hidden');
        $('#div_sucursal').addClass('text-primary');

        // Lógica adicional (si aplica)
        getInformationBaking();
        $('.btn').removeClass('btn-primary');

        // Habilita los botones dentro de la tabla
        $('#Tablabotones tbody button').prop('disabled', false);
    } else {
        // Si no hay sucursal seleccionada, deshabilitar los botones
        $('#div_horneado').addClass('hidden');
        $('#div_sucursal').removeClass('text-primary');
        $('#lbl_sucursal').text('');
        $('#lbl_horneado_pzas').text('0');
        $('#lbl_charolas_qty').text('0');
        $('#tblBaking tbody').html('');
        $('.btn').removeClass('btn-primary');
        $('#Tablabotones tbody button').prop('disabled', true);
    }
}


    function getInformationBaking() {

        $.post('/Controller/Baking.php', {
            action: 'ajax',
            request: 'getInformationBaking',
            id_sucursal: id_sucursal,
            fecha_actual: fecha_actual
        }, function(data) {
            if (data.response) {
                $('.btn').removeClass('btn-primary');
                $('#lbl_horneado_pzas').text(data.horneado_pzas);
                $('#lbl_charolas_qty').text(data.charolas_qty);

                $("#tblBaking tbody").html(data.tableRows);

            } else {
                $('.flashmessenger').html(data.msg);
            }
        }, 'json');
    }



    function bindSelect() {

        $('select').on('select2:opening', function(e) {

            e.preventDefault();

            if ($(this).prop('readonly') !== true) {
                $(this).unbind('select2:opening');
                $(this).select2('open');
            }

        });

    }



    function setTotalLabels() {

        var quantity = 0;

        var sum_quantity = 0;

        $('.quantity').each(function(e) {

            quantity = $(this).val();

            if (quantity == '') {
                quantity = 0;
            }

            sum_quantity += parseFloat(quantity);

        });



        var total_cost = 0;

        var sum_total_cost = 0;

        $('.total_cost').each(function(e) {

            total_cost = $(this).val();

            if (total_cost == '') {
                total_cost = 0;
            }

            sum_total_cost += parseFloat(total_cost);

        });



        var total_price = 0;

        var sum_total_price = 0;

        $('.total_price').each(function(e) {

            total_price = $(this).val();

            if (total_price == '') {
                total_price = 0;
            }

            sum_total_price += parseFloat(total_price);

        });



        $('._labelTotalQuantity').html(sum_quantity.toFixed(2));

        $('._labelTotalCost').html(sum_total_cost.toFixed(2));

        $('._labelTotalPrice').html(sum_total_price.toFixed(2));

    }



    $("#date").datetimepicker({
        format: "MM/DD/YYYY hh:mm A"
    });

    $('select').select2();



    $('._addDetail').on('click', function() {

        $.post('/Controller/Waste.php', {

            action: 'ajax',

            request: 'addDetail'

        }, function(data) {

            if (data.response) {

                $('#tblWaste').find('tbody').append(data.detail_string);

                $('select.product_id').prop('readonly', true);

                $('select.' + data.uuid).prop('readonly', false).select2();

                bindSelect();

            } else {

                $.alert({
                    content: data.msg,
                    title: "<i class='fa fa-info-circle'></i> Message",
                    columnClass: 'col-md-4 col-md-offset-4'
                });

            }

        }, 'json');

    });



    $('#tblWaste tbody').on('select2:selecting', 'tr td .product_id', function(e) {

        var that = this;

        var current_product_id = $(this).val();

        var new_product_id = e.params.args.data.id;

        var exist = $('select.product_id option[value="' + new_product_id + '"]:selected').length;



        if (exist > 0) {

            // $.alert({

            //     title: 'Mensaje!',

            //     content: 'Este producto ya esta en merma.',

            //     buttons: {

            //         ok: function() {

            //             $(that).val(current_product_id).trigger('change');

            //         }

            //     }

            // });

            $.confirm({
                theme: 'material',
                columnClass: 'col-md-6 col-md-offset-3',
                icon: 'fa fa-warning',
                title: 'Confirmar operacion !',
                content: 'El producto seleccionado ya existe en el registro de mermas, desea continuar?',
                buttons: {
                    cancel: {
                        text: 'No',
                        btnClass: 'btn-default col-md-4 pull-right',
                        action: function() {
                            $(this).remove();
                            $(that).val(current_product_id).trigger('change');
                        }
                    },
                    confirm: {
                        text: 'Si ',
                        btnClass: 'btn-primary col-md-4 pull-right',
                        action: function() {

                        }
                    }
                }
            });

        }

    });
    // $('#tblWaste tbody').on('select2:select', 'tr td .product_id', function() 
    $('#tblWaste tbody').on('select2:select', 'tr td .categoria', function() {

        var that = this;

        var current_category_id = $(this).val();

        var uuid = $(this).data('uuid');

        $('select.' + uuid).prop('readonly', false);

        $.post('/Controller/Waste.php', {

            action: 'ajax',

            request: 'getDataByCategory',

            category_id: current_category_id

        }, function(data) {

            if (data.response) {


                //$('select.' + uuid).select2('destroy');
                $('.s2' + uuid + '.product_id').select2('destroy');

                // $('.'+ uuid + '[product_id]').html(data.producto);
                // $('.'+ uuid + '[product_id]').select2();

                // $('.'+ uuid +'[product_id]').html(data.producto);
                // $('.'+ uuid +'[product_id]').select2();

                $('select.' + uuid + '.product_id').html(data.producto);
                $('select.' + uuid + '.product_id').select2();

            } else {

                $.alert({
                    content: data.msg,
                    title: "<i class='fa fa-info-circle'></i> Message",
                    columnClass: 'col-md-4 col-md-offset-4'
                });

            }

        }, 'json');

    });

    $('#tblBaking tbody').on('click', 'tr td ._delete', function() {

        var that = this;
        var id = $(that).data('id');
        $.confirm({

            theme: 'material',

            columnClass: 'col-md-6 col-md-offset-3',

            icon: 'fa fa-trash',

            title: 'Eliminar registro',

            content: 'Desea eliminar el registro ?',

            buttons: {

                cancel: {

                    text: 'No',

                    btnClass: 'btn-default col-md-4 pull-right',

                    action: function() {

                        $(this).remove();

                    }

                },

                confirm: {

                    text: 'Si ',

                    btnClass: 'btn-primary col-md-4 pull-right',

                    action: function() {

                        $.post('/Controller/Baking.php', {
                            action: 'ajax',
                            request: 'deleteBaking',
                            id: id
                        }, function(data) {
                            if (data.response) {
                                $('.flashmessenger').html(data.msg);
                                getInformationBaking();
                            }
                        }, 'json');

                    }

                }

            }

        });

        return null;

    });


    $('#tblWaste tbody').on('click', 'tr td ._edit', function() {

        bindSelect();

        $('select.product_id').prop('readonly', true);



        var uuid = $(this).data('uuid');

        $('select.' + uuid).prop('readonly', false);

    });



    $('#tblWaste').DataTable({
        paging: false,
        filter: true,
        "bInfo": false
    });

    $('#tblWaste_filter').hide();



    $('#tblWaste tbody').on('select2:select', 'tr td .product_id', function() {

        $('select.product_id').prop('readonly', true);



        var uuid = $(this).data('uuid');

        var quantity = $('.' + uuid + '.quantity').val();

        if (quantity == '') {
            quantity = 0;
        }



        $.post('/Controller/Waste.php', {

            action: 'ajax',

            request: 'getDataProduct',

            product_id: $(this).val()

        }, function(data) {

            if (data.response) {

                $('.' + uuid + '.cost').val(data.cost);

                $('.' + uuid + '.price').val(data.price);



                var total_cost = parseFloat(quantity) * parseFloat(data.cost);

                var total_price = parseFloat(quantity) * parseFloat(data.price);



                $('.' + uuid + '.total_cost').val(total_cost.toFixed(2));

                $('.' + uuid + '.total_price').val(total_price.toFixed(2));



                $('.' + uuid + '.quantity').focus().select();

                setTotalLabels();



            } else {

                $.alert({
                    content: data.msg,
                    title: "<i class='fa fa-info-circle'></i> Message",
                    columnClass: 'col-md-4 col-md-offset-4'
                });

            }



            bindSelect();



        }, 'json');

    });



    $('#tblWaste tbody').on('change', 'tr td .quantity', function() {

        var uuid = $(this).data('uuid');

        var quantity = $('.' + uuid + '.quantity').val();

        var cost = $('.' + uuid + '.cost').val();

        var price = $('.' + uuid + '.price').val();



        if (quantity == '') {
            quantity = 0;
        }

        if (cost == '') {
            cost = 0;
        }

        if (price == '') {
            price = 0;
        }



        var total_cost = parseFloat(quantity) * parseFloat(cost);

        var total_price = parseFloat(quantity) * parseFloat(price);



        $('.' + uuid + '.total_cost').val(total_cost.toFixed(2));

        $('.' + uuid + '.total_price').val(total_price.toFixed(2));



        setTotalLabels();

    });



    window.onload = function() {

        $('#tblWaste tbody tr td select').prop('readonly', true);

        bindSelect();

        setTotalLabels();



    };



    $("#attachments").fileinput({

        allowedFileExtensions: ["jpg", "png", "gif"]

    });
</script>