<section class="content-header">

    <h1><i class='fa-fw fa fa-recycle'></i> <?php echo $_translator->_getTranslation('Merma'); ?></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><a href="<?php echo ROOT_HOST ?>/Controller/Waste.php?action=list"><?php echo $_translator->_getTranslation('Lista de mermas') ?></a></li>

        <li class="active"><?php echo $_translator->_getTranslation('Merma'); ?></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 class="box-tools">

                <?php

                if ($action === 'edit') { ?>

                    <a href="Waste.php" class="btn btn-default"><i class='fa fa-plus'></i> <?php echo $_translator->_getTranslation('Agregar merma') ?></a>

                    <a class="btn btn-default _print" data-id="<?php echo $_form->getId() ?>" href="#" onclick="javascript: void window.open('Waste.php?action=export&format=pdf&flag=waste&id=<?php echo $_form->getId(); ?>','','width=700,height=500,status=1,scrollbars=1,resizable=1')"><i class="fa fa-print fa-"></i> <?php echo $_translator->_getTranslation('Imprimir') ?></a><?php

                                                                                                                                                                                                                                                                                                                                                                                    } ?>

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

        </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('Informacion general') ?></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="col-xs-12 col-md-12">

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

                                <?php $_form->showElement('store_id'); ?>

                                <?php $_form->showElement('date'); ?>

                                <?php $_form->showElement('comments'); ?>

                            </div>

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

                                <?php

                                if ($action == 'edit') {
                                    $_form->showElement('statusName');
                                } ?>

                                <?php

                                //$_form->showElement('attachments[]');

                                //echo $_waste->getListFiles($_form->getId());
                                ?>

                            </div>

                        </div>

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

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

                            <h4><?php echo $_translator->_getTranslation('Detalles de merma'); ?></h4>

                            <hr />

                            <table id="tblWaste" 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('Categoria'); ?></th>


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

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

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

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

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

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

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php echo $_stringDetails ?>

                                </tbody>

                            </table>

                            <br />

                            <?php $element = $_form->getElement('agregar_producto'); ?>

                            <?php echo $_form->createElement($element); ?>

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

                        </div>

                        <div class="col-lg-3 col-md-3 pull-right">

                            <table id="waste_totals" class="table-condensed" style='width: 100%'>

                                <tbody>

                                    <tr>

                                        <th class="text-right" colspan="2" style="border: 0px;"><?php echo $_translator->_getTranslation('Total unidades') ?></th>

                                        <td class="_labelTotalQuantity text-right col-lg-3 col-md-3" style="border: 0px;border-bottom: 1px solid #eee"></td>

                                    </tr>

                                    <tr>

                                        <th class="text-right" colspan="2" style="border: 0px;"><?php echo $_translator->_getTranslation('Total costo') ?> $</th>

                                        <td class="_labelTotalCost text-right col-lg-3 col-md-3" style="border: 0px;border-bottom: 1px solid #eee"></td>

                                    </tr>

                                    <tr>

                                        <th class="text-right" colspan="2" style="border: 0px;"><?php echo $_translator->_getTranslation('Total venta') ?> $</th>

                                        <td class="_labelTotalPrice text-right col-lg-3 col-md-3" style="border: 0px;border-bottom: 1px solid #eee"></td>

                                    </tr>

                                </tbody>

                            </table>

                        </div>

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

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

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

                            <?php echo $_form->createOnlyElement($_form->getElement('attachments[]')); ?>

                        </div>

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

                            <?php

                            if ($action == 'edit') {

                                echo $_waste->showImages($_form->getId());
                            }

                            ?>

                        </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">

                <?php $element = $_form->getElement('terminar'); ?>

                <?php echo $_form->createElement($element); ?>

            </div>

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

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

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

</section>

<style>
    .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;

    }
</style>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.0/font/bootstrap-icons.css">

<script>
    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');

    });

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

        var that = this;

        $.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() {

                        $(that).closest('tr').remove();

                    }

                }

            }

        });

        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>