<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<div class="box">
    <div class="box-header">
        <h2 class="blue"><i class="fa fa-trash"></i><?= lang('Agregar Merma'); ?></h2>
    </div>
    <div class="box-content">
        <?= form_open("admin/merma/add", ['id' => 'add-merma-form']); ?>

        <div class="row">
            <div class="col-lg-12">

                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <?= lang("Referencia", "reference_no"); ?>
                            <?= form_input('reference_no', set_value('reference_no', 'MERMA-'.date('YmdHis')), 'class="form-control" id="reference_no" readonly'); ?>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <?= lang("Almacén", "warehouse_id"); ?>
                            <select name="warehouse_id" id="warehouse_id" class="form-control" required>
                                <option value=""><?= lang("Seleccione Almacén"); ?></option>
                                <?php foreach ($warehouses as $wh): ?>
                                    <option value="<?= $wh->id ?>"><?= $wh->name ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <?= lang("Notas", "note"); ?>
                            <?= form_textarea('note', set_value('note'), 'class="form-control" id="note" style="height:100px;"'); ?>
                        </div>
                    </div>
                </div>

                <div class="clearfix"></div>

                <div class="control-group table-group">
                    <label class="table-label"><?= lang("Productos de Merma"); ?></label>

                    <div class="controls table-controls">
                        <table id="mermaTable" class="table items table-striped table-bordered table-condensed table-hover sortable_table">
                            <thead>
                                <tr>
                                    <th><?= lang("Producto"); ?></th>
                                    <th><?= lang("Cantidad"); ?></th>
                                    <th><?= lang("Costo"); ?></th>
                                    <th><?= lang("Subtotal"); ?></th>
                                    <th style="width:30px; text-align:center;">
                                        <i class="fa fa-trash-o" style="opacity:0.5;"></i>
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                            <tfoot></tfoot>
                        </table>
                    </div>
                </div>

                <div class="clearfix"></div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="fprom-group">
                            <?= form_submit('add_merma', lang("Guardar Merma"), 'class="btn btn-primary" id="add_merma"'); ?>
                            <a href="<?= site_url('admin/merma'); ?>" class="btn btn-danger"><?= lang("Cancelar"); ?></a>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?= form_close(); ?>
    </div>
</div>

<!-- Modal para agregar productos -->
<div class="modal fade" id="prModal" tabindex="-1" role="dialog" aria-labelledby="prModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span>&times;</span></button>
                <h4 class="modal-title" id="prModalLabel"><?= lang('Agregar Producto a Merma'); ?></h4>
            </div>
            <div class="modal-body">
                <div class="input-group">
                    <input type="text" name="add_product" value="" class="form-control" id="add_item" placeholder="<?= lang("Buscar producto por código o nombre") ?>">
                    <div class="input-group-addon no-print" style="padding: 2px 5px;">
                        <a href="#" id="addItemManually" class="external">
                            <i class="fa fa-plus-circle" id="addIcon"></i>
                        </a>
                    </div>
                </div>
                <div id="suggestions"></div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    // Script adaptado del retorno de ventas
    var merma_items = {};

    $(document).ready(function () {
        // Buscar producto
        $('#add_item').autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: 'get',
                    url: '<?= site_url('admin/products/suggestions'); ?>',
                    dataType: 'json',
                    data: {
                        term: request.term,
                        warehouse_id: $("#warehouse_id").val()
                    },
                    success: function (data) {
                        response(data);
                    }
                });
            },
            minLength: 1,
            select: function (event, ui) {
                event.preventDefault();
                if (ui.item.id !== 0) {
                    add_product_to_table(ui.item);
                    $(this).val('');
                }
            }
        });
    });

    function add_product_to_table(item) {
        if (item) {
            var row = $('<tr>' +
                '<td>' + item.label + '<input type="hidden" name="products[' + item.id + '][product_id]" value="' + item.id + '"></td>' +
                '<td><input type="number" class="form-control text-center" name="products[' + item.id + '][quantity]" value="1" min="1"></td>' +
                '<td><input type="text" class="form-control text-right" name="products[' + item.id + '][cost]" value="' + item.cost + '" readonly></td>' +
                '<td class="text-right"><span class="subtotal">' + item.cost + '</span></td>' +
                '<td class="text-center"><i class="fa fa-trash-o tip pointer redel"></i></td>' +
                '</tr>');

            $('#mermaTable tbody').append(row);
            recalc_subtotals();
        }
    }

    $(document).on('click', '.redel', function () {
        $(this).closest('tr').remove();
        recalc_subtotals();
    });

    function recalc_subtotals() {
        var total = 0;
        $('#mermaTable tbody tr').each(function () {
            var qty = parseFloat($(this).find('input[name$="[quantity]"]').val()) || 0;
            var cost = parseFloat($(this).find('input[name$="[cost]"]').val()) || 0;
            var subtotal = qty * cost;
            $(this).find('.subtotal').text(subtotal.toFixed(2));
            total += subtotal;
        });
        $('#mermaTable tfoot').html('<tr><th colspan="3" class="text-right">Total</th><th class="text-right">' + total.toFixed(2) + '</th><th></th></tr>');
    }

    $(document).on('input', 'input[name$="[quantity]"]', function () {
        recalc_subtotals();
    });
</script>
