<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/dt-1.13.1/af-2.5.1/b-2.3.3/b-colvis-2.3.3/b-html5-2.3.3/b-print-2.3.3/fc-4.2.1/fh-3.3.1/datatables.min.css" />

<script type="text/javascript" src="https://cdn.datatables.net/v/bs/jszip-2.5.0/dt-1.13.1/af-2.5.1/b-2.3.3/b-colvis-2.3.3/b-html5-2.3.3/b-print-2.3.3/fc-4.2.1/fh-3.3.1/datatables.min.js"></script>



<div class="box box-primary">

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

        <h3 class="box-title"><i class="fa fa-th-large"></i> <?php echo $_translator->_getTranslation(ucfirst($_reporte->getTituloReporte())); ?></h3>

        <div class="box-tools pull-right">

            <a class="btn btn-default" href="<?php echo $_reporte->getStringToSendArrayGET() .'&action=create&output=excel' ?>"><i class="fa fa-file-excel-o"></i> <?php echo $_translator->_getTranslation('Exportar a excel') ?></a>

            <!--<a class="btn btn-default" href="<?php echo $_reporte->getStringToSendGET() . '&enviarPorMail' ?>" class="linkSendMail" data-toggle='modal' data-target='#modalSendReportToMail'><i class="fa fa-envelope"></i> <?php echo $_translator->_getTranslation('Enviar por correo') ?></a>-->

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

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

    <div class="box-body">

        <?php

        $data = $_reporte->getReporte();

        if ($data == null) {

            echo "There is no information";

            exit;
        }

        $sucursales = $data['stores'];

        $data = $data['data'];

        ?>

        <div class="table-responsive">

            <div>

                Ocultar/Mostrar Sucursal: <br />

                <a class='toggle-hide-all' style="cursor: pointer">Ocultar todas | </a>

                <a class='toggle-show-all' style="cursor: pointer">Mostrar todas | </a>

                <?php

                $storeColum = 6;

                foreach ($sucursales as $key => $sucursal) { ?>

                    <a class="toggle-vis" data-column="<?php echo $storeColum ?>" style="cursor: pointer"><?php echo $sucursal; ?></a> | <?php

                                                                                                                                            $storeColum++;
                                                                                                                                        } ?>



            </div>

            <br />

            <table id="tblReport" class="table table-striped table-bordered table-condensed table-hover" style="font-size: 12px">

                <thead class="table-header">

                    <tr>

                        <th class="text-center"></th>

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

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

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

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

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



                        <?php foreach ($sucursales as $key => $sucursal) { ?>
                            <th class="text-center">
                                <?php $sucursal = str_replace(' ', '', $sucursal);
                                ?>
                                
                                <?php echo $sucursal; ?><br>
                                Cant | $
                            </th>
                        <?php } ?>

                    </tr>

                </thead>

                <tfoot>

                    <th></th>

                    <th class="filter text-center"><?php echo $_translator->_getTranslation('Codigo'); ?></th>

                    <th class="filter text-center"><?php echo $_translator->_getTranslation('Descripcion'); ?></th>

                    <th class="filter text-center"><?php echo $_translator->_getTranslation('UM'); ?></th>

                    <th class="filter text-center"><?php echo $_translator->_getTranslation('Categoria'); ?></th>

                    <th class="filter text-center"><?php echo $_translator->_getTranslation('Costo'); ?></th>


                    <?php foreach ($sucursales as $key => $sucursal) { ?>
                        <th class="filter text-center">
                            <?php $sucursal = str_replace(' ', '', $sucursal);
                             ?>
                            
                            <?php echo $sucursal; ?><br>
                            Cant | $
                        </th>
                    <?php } ?>

                </tfoot>

                <tbody>

                    <?php

                    $login = new Login();

                    $currentSucursal = $login->getStoreId();

                    $i = 1;

                    foreach ($data as $row) { ?>

                        <tr>

                            <td><?php echo $i;
                                $i++; ?></td>

                            <td class="text-center"><?php echo $row['code']; ?></td>

                            <td class="text-center" style="white-space: nowrap"><?php echo $row['description']; ?></td>

                            <td class="text-center" style="white-space: nowrap"><?php echo $row['um']; ?></td>

                            <td class="text-center" style="white-space: nowrap"><?php echo $row['category']; ?></td>

                            <td class="text-center" style="white-space: nowrap"><?php echo number_format($row['cost'], 2); ?></td>
                            <?php foreach ($sucursales as $idSucursal => $sucursal) {

                                $class = '';

                                if ($currentSucursal == $idSucursal || $login->getRole() == '1') {
                                    $class = 'editInventory';
                                }

                            ?>
                                <td id="<?php echo $row['id_product'] . '_' . $idSucursal ?>" class="<?php echo $class; ?> text-center" style="white-space: nowrap;"
                                    data-idproduct="<?php echo $row['id_product'] ?>"

                                    data-productname="<?php echo $row['description'] ?>"

                                    data-idstore="<?php echo $idSucursal; ?>"

                                    data-storename="<?php echo $sucursal; ?>"

                                    data-cost="<?php echo $row['cost']; ?>"
                                    
                                    data-stock="<?php echo $row["$idSucursal"]; ?>">

                                    <?php $sucursal = str_replace(' ', '', $sucursal); ?>
                                
                                    <?php echo number_format($row["$idSucursal"], 2); ?> |
                                    <?php $total_cost = (float)$row["$idSucursal"] * (float)$row['cost']; ?>
                                     $ <?php echo number_format($total_cost, 2); ?>
                                </td>
                            <?php } ?>
                            
                         



                        </tr><?php

                            } ?>

                </tbody>

            </table>

        </div>

    </div>

</div>

<style>
    tfoot {

        display: table-header-group;

    }



    .verticalTableHeader {

        text-align: center;

        white-space: nowrap;

        g-origin: 50% 50%;

        -webkit-transform: rotate(-90deg);

        -moz-transform: rotate(-90deg);

        -ms-transform: rotate(-90deg);

        -o-transform: rotate(-90deg);

        transform: rotate(-90deg);

        border: 0px !important;



    }

    .verticalTableHeader p {

        margin: 0 -100%;

        display: inline-block;

    }

    .verticalTableHeader p:before {

        content: '';

        width: 0;

        padding-top: 110%;
        /* takes width as reference, + 10% for faking some extra padding */

        display: inline-block;

        vertical-align: middle;

    }



    th.sorting.verticalTableHeader::after,

    th.sorting_asc.verticalTableHeader::after,

    th.sorting_desc.verticalTableHeader::after {
        content: "" !important;
    }



    /* Set !important rule to override default colors */

    .tr_active {

        background: gold !important;

    }
</style>

<script type="text/javascript" language="javascript">
    $('.editInventory').click(function() {

        $('#idProduct').val($(this).data('idproduct'));

        $('#idStore').val($(this).data('idstore'));

        $('#stock').val($(this).data('stock'));

        $('#notes').val($(this).data('notes'));

        $('#productName').html($(this).data('productname'));

        $('#storeName').html($(this).data('storename'));



        $('#modalEditInventory').modal('show');

    });



    const table = $('#tblReport').DataTable({

        paginate: false,

        filter: true,

        aaSorting: [],

        scrollY: '700px',

        scrollX: 'true',

        fixedColumns: {
            left: 6
        }

    });



    $('#tblReport').removeClass('display').addClass('table table-striped table-bordered');

    $("#tblReport tr").on("click", function() {

        //loop through all td elements in the row

        $(this).find("td").each(function(i) {

            //toggle between adding/removing the 'active' class

            $(this).toggleClass('tr_active');

        });

    });



    /*$('#tblReport tfoot th.filter').each( function () {

           $(this).html( '<input type="text" placeholder="Search" style="width:100%" />' );

       } );  



       var table = $('#tblReport').DataTable();

       // Apply the search

       table.columns().every( function () {

           var that = this; 

           $( 'input', this.footer() ).on( 'keyup change', function () {

               if ( that.search() !== this.value ) {

                   that

                       .search (this.value.replace("/;/g", "|"), true, false)

                       .draw();

               }

           } );

       } );*/



    $('.editInventory').on('click', function(e) {

        if ($(e.target).is('td')) {

            
            const currentStock = $(this).attr('data-stock'); // Obtener el valor actualizado del atributo data-stock

            const input = document.createElement('input');

            input.setAttribute('type', 'text');

            // input.setAttribute('value', $(this).data('stock'));
            input.setAttribute('value', currentStock); // Usar el valor actualizado


            input.setAttribute('data-id', $(this).attr('id'));

            input.setAttribute('class', 'form-control');

            input.setAttribute('style', 'width:100%');



            $(this).html(input);

            $(input).focus().select();



            $(input).on('blur', function() {

                var tdParent = $(this).parent('td');

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

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

                    action: 'ajax',

                    request: 'updateInventory',

                    id: $(this).data('id'),

                    stock: $(this).val()

                }, function(data) {

                    // if (data.response) {

                    //     tdParent.html(stock);

                    // }
                    if (data.response) {
                    // Actualiza el contenido de la celda con el nuevo valor
                    tdParent.html(stock + ' | $' + (parseFloat(stock) * parseFloat(tdParent.data('cost'))).toFixed(2));

                    // Actualiza el atributo data-stock con el nuevo valor
                    tdParent.attr('data-stock', stock);
                } else {
                    
                    tdParent.html(tdParent.data('stock') + ' | $' + (parseFloat(tdParent.data('stock')) * parseFloat(tdParent.data('cost'))).toFixed(2));
                }

                }, 'json');

            });

        }

    });



    document.querySelectorAll('a.toggle-vis').forEach((el) => {

        el.addEventListener('click', function(e) {

            e.preventDefault();



            let columnIdx = e.target.getAttribute('data-column');

            let column = table.column(columnIdx);



            // Toggle the visibility

            column.visible(!column.visible());

        });

    })



    $('.toggle-hide-all').on('click', function() {



        $('a.toggle-vis').each(function() {



            let columnIdx = $(this).data('column');

            let column = table.column(columnIdx);

            column.visible(false);



        });



    })



    $('.toggle-show-all').on('click', function() {

        $('a.toggle-vis').each(function() {



            let columnIdx = $(this).data('column');

            let column = table.column(columnIdx);

            column.visible(true);

        });

    })
</script>