<?php (defined('BASEPATH')) OR exit('No direct script access allowed'); ?>
<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box box-primary">
                <div class="box-header">
                    <h3 class="box-title"><?= lang('enter_info'); ?></h3>
                </div>
                <div class="box-body">
                    <div class="col-lg-12">
                        <?= form_open_multipart("products/add", 'class="validation"');?>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <?= lang('type', 'type'); ?>
                                    <?php $opts = array('standard' => lang('standard'), 'service' => lang('service')); ?>
                                    <?= form_dropdown('type', $opts, set_value('type', 'standard'), 'class="form-control tip select2" id="type"  required="required" style="width:100%;"'); ?>
                                </div>
                                <div class="form-group">
                                    <?= lang('name', 'name'); ?>
                                    <?= form_input('name', set_value('name'), 'class="form-control tip" id="name"  required="required"'); ?>
                                </div>

                                <!-- CÓDIGO DO PRODUTO-->


                                <script type="text/javascript">
                                function gerar() {

                                    var alfabeto = "";
                                    //var alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWYZ";
                                    // letras aleatorias
                                    var letras = [];
                                    for (var i = 0; i < 4; ++i)
                                        letras[i] = alfabeto.charAt(Math.floor(Math.random() * 25));

                                    // numero aleatorios
                                    var numeros = [];
                                    for (var i = 0; i < 6; ++i) {
                                        var sorteio = Math.floor(Math.random() * 9);

                                        if (sorteio == 0)
                                            sorteio = 1; // 1 - 9

                                        numeros[i] = sorteio;
                                    }

                                    var senha = letras.join('') + numeros.join('');

                                    document.getElementById('code').value = senha;
                                }
                                </script>


                                <div class="form-group">
                                    <?= lang('code', 'code'); ?> <?= lang('can_use_barcode'); ?>
                                    <div class="input-group">

                                        <?= form_input('code', set_value('code'), 'class="form-control tip" id="code"  required="required"'); ?>
                                        
                                        <span class="input-group-addon pointer" id="random_num" onclick="javascript:gerar()"
                                            style="padding: 1px 10px;">
                                            <i class="fa fa-random" ></i> Gerar código </span></div>

                                </div>

                                <!-- FIM -->


                                <div class="form-group all">
                                    <?= lang("barcode_symbology", "barcode_symbology") ?>
                                    <?php
                                    $bs = array('ean8' => 'EAN8', 'ean13' => 'EAN13', 'code25' => 'Code25', 'code39' => 'Code39', 'code128' => 'Code128', 'upca ' => 'UPC-A', 'upce' => 'UPC-E');
                                    echo form_dropdown('barcode_symbology', $bs, set_value('barcode_symbology', 'ean13'), 'class="form-control select2" id="barcode_symbology" required="required" style="width:100%;"');
                                    ?>
                                </div>

                                <div class="form-group">
                                    <?= lang('category', 'category'); ?>
                                    <?php
                                    $cat[''] = lang("select")." ".lang("category");
                                    foreach($categories as $category) {
                                        $cat[$category->id] = $category->name;
                                    }
                                    ?>
                                    <?= form_dropdown('category', $cat, set_value('category'), 'class="form-control select2 tip" id="category"  required="required" style="width:100%;"'); ?>
                                </div>

                                <div class="form-group">
                                    <?= lang('cost', 'cost'); ?>
                                    <?= form_input('cost', set_value('cost'),  'class="form-control tip dinheiroinput" id="cost"  required="required"'); ?>
                                </div>

                                <div class="form-group">
                                    <label for="unit">Unidade de medida</label>
                                    <?php $opts = array('UN' => "Unidade", 'KG' => "Kilograma", 'PC' => 'Peça', 'CX' => 'CX', 'DZ' => 'DZ', 'CJ' => 'CJ','MT' => 'MT','M2' => 'M2','M3' => 'M3','FRD' => 'FRD','PCT' => 'PCT'); ?>
                                    <?= form_dropdown('unit', $opts, set_value('unit', 'UN'), 'class="form-control tip select2" id="unit"  required="required" style="width:100%;"'); ?>
                                </div>

                                <div class="form-group">
                                    <?= lang('price', 'price'); ?>
                                    <?= form_input('price', set_value('price'), 'class="form-control tip dinheiroinput" id="price"  required="required"'); ?>
                                </div>

                                <input name='product_tax' type="hidden" value='0' id="product_tax">
                                <input name='tax_method' type="hidden" value='1' id="tax_method">

                                <div class="form-group" id="st">
                                    <?= lang('Quantidade em estoque', 'Quantidade em estoque'); ?>
                                    <?= form_input('quantity', set_value('quantity', 0), 'class="form-control tip" id="quantity"  required="required"'); ?>
                                </div>

                                <div class="form-group" id="st">
                                    <?= lang('alert_quantity', 'alert_quantity'); ?>
                                    <?= form_input('alert_quantity', set_value('alert_quantity', 0), 'class="form-control tip" id="alert_quantity"  required="required"'); ?>
                                </div>

                                <div class="form-group">
                                    <?= lang('image', 'image'); ?> PNG, JPG, GIF, (300px x 300px)
                                    <input type="file" name="userfile" id="image">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div id="ct" style="display:none;">

                                    <div class="form-group">
                                        <?= lang("add_product", "add_item"); ?>
                                        <?php echo form_input('add_item', '', 'class="form-control ttip" id="add_item" data-placement="top" data-trigger="focus" data-bv-notEmpty-message="' . lang('please_add_items_below') . '" placeholder="' . $this->lang->line("add_item") . '"'); ?>
                                    </div>
                                    <div class="control-group table-group">
                                        <label class="table-label" for="combo"><?= lang("combo_products"); ?></label>

                                        <div class="controls table-controls">
                                            <table id="prTable"
                                                class="table items table-striped table-bordered table-condensed table-hover">
                                                <thead>
                                                    <tr>
                                                        <th class="col-xs-9">
                                                            <?= lang("product_name") . " (" . $this->lang->line("product_code") . ")"; ?>
                                                        </th>
                                                        <th class="col-xs-2"><?= lang("quantity"); ?></th>
                                                        <th class=" col-xs-1 text-center"><i
                                                                class="fa fa-trash-o trash-opacity-50"></i></th>
                                                    </tr>
                                                </thead>
                                                <tbody></tbody>
                                            </table>
                                        </div>
                                    </div>

                                </div>
                                <h3>Configuração de Impostos</h3>
                                <div class="form-group">
                                    <label for="origem">Origem do produto</label>
                                    <?php $tm = array("" => "Selecione", 0 => '0 - Nacional, exceto as indicadas nos códigos 3, 4, 5 e 8', 1 => '1 - Estrangeira - Importação direta, exceto a indicada no código 6', 2 => '2 - Estrangeira - Adquirida no mercado interno, exceto a indicada no código 7', 3 => '3 - Nacional, mercadoria ou bem com Conteúdo de Importação superior a 40% e inferior ou igual a 70%', 4 => '4 - Nacional, cuja produção tenha sido feita em conformidade com os processos produtivos básicos de que tratam as legislações citadas nos Ajustes', 5 => '5 - Nacional, mercadoria ou bem com Conteúdo de Importação inferior ou igual a 40%', 6 => '6 - Estrangeira - Importação direta, sem similar nacional, constante em lista da CAMEX e gás natural', 7 => '7 - Estrangeira - Adquirida no mercado interno, sem similar nacional, constante lista CAMEX e gás natural', 8 => '8 - Nacional, mercadoria ou bem com Conteúdo de Importação superior a 70%'); ?>
                                    <?= form_dropdown('origem', $tm, set_value('origem'), 'class="form-control tip select2" id="origem"  required="required" style="width:100%;"'); ?>
                                </div>
                                <div class="form-group">
                                    <label for="cfop">CFOP (Dentro do Estado)</label>

                                    <?php require_once "cfop.php"; ?>
                                    <?= form_dropdown('cfop', $cfop, '', 'class="form-control tip select2" id="cfop"  required="required" style="width:100%;"'); ?>
                                </div>
                                <div class="form-group">
                                    <label for="cfop2">CFOP (Fora do Estado)</label>

                                    <?php $cfop = array("" => "Selecione", 6101 => '6.101 - Venda de produção do estabelecimento', 6102 => '6.102 - Venda de mercadoria adquirida ou recebida de terceiros', 6103 => '6.103 - Venda de produção do estabelecimento, efetuada fora do estabelecimento',6104 => '6.104 - Venda de mercadoria adquirida ou recebida de terceiros, efetuada fora do estabelecimento',6933 => '6.933 - Prestação de serviço tributado pelo ISSQN.'); ?>
                                    <?= form_dropdown('cfop2', $cfop, '', 'class="form-control tip select2" id="cfop2"  required="required" style="width:100%;"'); ?>
                                </div>

                                <div class="form-group">
                                    <label for="ncm">Código NCM</label>
                                    <?= form_input('ncm', set_value('ncm', ""), 'class="form-control tip" id="ncm"'); ?>
                                    <?php
                                   /* $cest_val[''] = "Selecione o Código NCM / CEST";
                                    foreach($cest as $cesti) {
                                        $cest_val[$cesti->legal_tbc] = $cesti->descricao_tbc;
                                    }
																	*/
                                    ?>
                                    <? //=form_dropdown('cest', $cest_val, set_value('cest'), 'class="form-control tip select2" id="cest"  required="required"'); ?>
                                </div>
                                <div class="form-group">
                                    <label for="cest">Código CEST</label>
                                    <?= form_input('cest', set_value('cest', ""), 'class="form-control tip" id="cest"'); ?>
                                </div>

                                <input name='product_tax' value='0' type="hidden">
                                <input name='tax_method' value='1' type="hidden">
                                <div class="form-group">
                                    <label for="impostos">Grupo de Impostos</label>

                                    <?php
                                    $imp[''] = lang("select");
                                    foreach($impostos as $imposto) {
                                        if($imposto->tipo==1){ $impadd = "Produto - "; }else{ $impadd = "Serviço - "; }
                                        $imp[$imposto->id] = $impadd.$imposto->nome;
                                    }
                                    ?>
                                    <?= form_dropdown('imposto', $imp, set_value('imposto'), 'class="form-control select2 tip" id="impostos" required="required" style="width:100%;"'); ?>
                                </div>
                            </div>
                        </div>




                        <div class="form-group">
                            <?= lang('details', 'details'); ?>
                            <?= form_textarea('details', set_value('details'), 'class="form-control tip redactor" id="details"'); ?>
                        </div>
                        <div class="form-group">
                            <?= form_submit('add_product', lang('add_product'), 'class="btn btn-primary"'); ?>
                        </div>
                        <?= form_close();?>
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
    </div>
</section>

<script src="<?= $assets ?>dist/js/jquery-ui.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
    (function(e) {
        e.fn.priceFormat = function(t) {
            var n = {
                prefix: "US$ ",
                suffix: "",
                centsSeparator: ".",
                thousandsSeparator: ",",
                limit: false,
                centsLimit: 2,
                clearPrefix: false,
                clearSufix: false,
                allowNegative: false,
                insertPlusSign: false,
                clearOnEmpty: false
            };
            var t = e.extend(n, t);
            return this.each(function() {
                function m(e) {
                    if (n.is("input")) n.val(e);
                    else n.html(e)
                }

                function g() {
                    if (n.is("input")) r = n.val();
                    else r = n.html();
                    return r
                }

                function y(e) {
                    var t = "";
                    for (var n = 0; n < e.length; n++) {
                        char_ = e.charAt(n);
                        if (t.length == 0 && char_ == 0) char_ = false;
                        if (char_ && char_.match(i)) {
                            if (f) {
                                if (t.length < f) t = t + char_
                            } else {
                                t = t + char_
                            }
                        }
                    }
                    return t
                }

                function b(e) {
                    while (e.length < l + 1) e = "0" + e;
                    return e
                }

                function w(t, n) {
                    if (!n && (t === "" || t == w("0", true)) && v) return "";
                    var r = b(y(t));
                    var i = "";
                    var f = 0;
                    if (l == 0) {
                        u = "";
                        c = ""
                    }
                    var c = r.substr(r.length - l, l);
                    var h = r.substr(0, r.length - l);
                    r = l == 0 ? h : h + u + c;
                    if (a || e.trim(a) != "") {
                        for (var m = h.length; m > 0; m--) {
                            char_ = h.substr(m - 1, 1);
                            f++;
                            if (f % 3 == 0) char_ = a + char_;
                            i = char_ + i
                        }
                        if (i.substr(0, 1) == a) i = i.substring(1, i.length);
                        r = l == 0 ? i : i + u + c
                    }
                    if (p && (h != 0 || c != 0)) {
                        if (t.indexOf("-") != -1 && t.indexOf("+") < t.indexOf("-")) {
                            r = "-" + r
                        } else {
                            if (!d) r = "" + r;
                            else r = "+" + r
                        }
                    }
                    if (s) r = s + r;
                    if (o) r = r + o;
                    return r
                }

                function E(e) {
                    var t = e.keyCode ? e.keyCode : e.which;
                    var n = String.fromCharCode(t);
                    var i = false;
                    var s = r;
                    var o = w(s + n);
                    if (t >= 48 && t <= 57 || t >= 96 && t <= 105) i = true;
                    if (t == 8) i = true;
                    if (t == 9) i = true;
                    if (t == 13) i = true;
                    if (t == 46) i = true;
                    if (t == 37) i = true;
                    if (t == 39) i = true;
                    if (p && (t == 189 || t == 109 || t == 173)) i = true;
                    if (d && (t == 187 || t == 107 || t == 61)) i = true;
                    if (!i) {
                        e.preventDefault();
                        e.stopPropagation();
                        if (s != o) m(o)
                    }
                }

                function S() {
                    var e = g();
                    var t = w(e);
                    if (e != t) m(t);
                    if (parseFloat(e) == 0 && v) m("")
                }

                function x() {
                    n.val(s + g())
                }

                function T() {
                    n.val(g() + o)
                }

                function N() {
                    if (e.trim(s) != "" && c) {
                        var t = g().split(s);
                        m(t[1])
                    }
                }

                function C() {
                    if (e.trim(o) != "" && h) {
                        var t = g().split(o);
                        m(t[0])
                    }
                }
                var n = e(this);
                var r = "";
                var i = /[0-9]/;
                if (n.is("input")) r = n.val();
                else r = n.html();
                var s = t.prefix;
                var o = t.suffix;
                var u = t.centsSeparator;
                var a = t.thousandsSeparator;
                var f = t.limit;
                var l = t.centsLimit;
                var c = t.clearPrefix;
                var h = t.clearSuffix;
                var p = t.allowNegative;
                var d = t.insertPlusSign;
                var v = t.clearOnEmpty;
                if (d) p = true;
                n.bind("keydown.price_format", E);
                n.bind("keyup.price_format", S);
                n.bind("focusout.price_format", S);
                if (c) {
                    n.bind("focusout.price_format", function() {
                        N()
                    });
                    n.bind("focusin.price_format", function() {
                        x()
                    })
                }
                if (h) {
                    n.bind("focusout.price_format", function() {
                        C()
                    });
                    n.bind("focusin.price_format", function() {
                        T()
                    })
                }
                if (g().length > 0) {
                    S();
                    N();
                    C()
                }
            })
        };
        e.fn.unpriceFormat = function() {
            return e(this).unbind(".price_format")
        };
        e.fn.unmask = function() {
            var t;
            var n = "";
            if (e(this).is("input")) t = e(this).val();
            else t = e(this).html();
            for (var r in t) {
                if (!isNaN(t[r]) || t[r] == "-") n += t[r]
            }
            return n
        }
    })(jQuery)
    $('.dinheiroinput').priceFormat({
        prefix: '',
        centsSeparator: ',',
        thousandsSeparator: '.'
    });
});
</script>
<script type="text/javascript" charset="utf-8">
var price = 0;
cost = 0;
items = {};
$(document).ready(function() {
    $('#type').change(function(e) {
        var type = $(this).val();
        if (type == 'combo') {
            $('#st').slideUp();
            $('#ct').slideDown();
            //$('#cost').attr('readonly', true);
        } else if (type == 'service') {
            $('#st').slideUp();
            $('#ct').slideUp();
            //$('#cost').attr('readonly', false);
        } else {
            $('#ct').slideUp();
            $('#st').slideDown();
            //$('#cost').attr('readonly', false);
        }
    });

    $("#add_item").autocomplete({
        source: '<?= site_url('
        products / suggestions '); ?>',
        minLength: 1,
        autoFocus: false,
        delay: 200,
        response: function(event, ui) {
            if ($(this).val().length >= 16 && ui.content[0].id == 0) {
                bootbox.alert('<?= lang('
                    no_product_found ') ?>',
                    function() {
                        $('#add_item').focus();
                    });
                $(this).val('');
            } else if (ui.content.length == 1 && ui.content[0].id != 0) {
                ui.item = ui.content[0];
                $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
                $(this).autocomplete('close');
                $(this).removeClass('ui-autocomplete-loading');
            } else if (ui.content.length == 1 && ui.content[0].id == 0) {
                bootbox.alert('<?= lang('
                    no_product_found ') ?>',
                    function() {
                        $('#add_item').focus();
                    });
                $(this).val('');

            }
        },
        select: function(event, ui) {
            event.preventDefault();
            if (ui.item.id !== 0) {
                var row = add_product_item(ui.item);
                if (row) {
                    $(this).val('');
                }
            } else {
                bootbox.alert('<?= lang('
                    no_product_found ') ?>');
            }
        }
    });
    $('#add_item').bind('keypress', function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            $(this).autocomplete("search");
        }
    });

    $(document).on('click', '.del', function() {
        var id = $(this).attr('id');
        delete items[id];
        $(this).closest('#row_' + id).remove();
    });


    $(document).on('change', '.rqty', function() {
        var item_id = $(this).attr('data-item');
        items[item_id].row.qty = (parseFloat($(this).val())).toFixed(2);
        add_product_item(null, 1);
    });

    $(document).on('change', '.rprice', function() {
        var item_id = $(this).attr('data-item');
        items[item_id].row.price = (parseFloat($(this).val())).toFixed(2);
        add_product_item(null, 1);
    });

    function add_product_item(item, noitem) {
        if (item == null && noitem == null) {
            return false;
        }
        if (noitem != 1) {
            item_id = item.row.id;
            if (items[item_id]) {
                items[item_id].row.qty = (parseFloat(items[item_id].row.qty) + 1).toFixed(2);
            } else {
                items[item_id] = item;
            }
        }
        price = 0;
        cost = 0;

        $("#prTable tbody").empty();
        $.each(items, function() {
            var item = this.row;
            var row_no = item.id;
            var newTr = $('<tr id="row_' + row_no + '" class="item_' + item.id + '"></tr>');
            tr_html = '<td><input name="combo_item_id[]" type="hidden" value="' + item.id +
                '"><input name="combo_item_code[]" type="hidden" value="' + item.code +
                '"><input name="combo_item_name[]" type="hidden" value="' + item.name +
                '"><input name="combo_item_cost[]" type="hidden" value="' + item.cost +
                '"><span id="name_' + row_no + '">' + item.name + ' (' + item.code + ')</span></td>';
            tr_html +=
                '<td><input class="form-control text-center rqty" name="combo_item_quantity[]" type="text" value="' +
                formatDecimal(item.qty) + '" data-id="' + row_no + '" data-item="' + item.id +
                '" id="quantity_' + row_no + '" onClick="this.select();"></td>';
            //tr_html += '<td><input class="form-control text-center rprice" name="combo_item_price[]" type="text" value="' + formatDecimal(item.price) + '" data-id="' + row_no + '" data-item="' + item.id + '" id="combo_item_price_' + row_no + '" onClick="this.select();"></td>';
            tr_html += '<td class="text-center"><i class="fa fa-times tip del" id="' + row_no +
                '" title="Remove" style="cursor:pointer;"></i></td>';
            newTr.html(tr_html);
            newTr.prependTo("#prTable");
            //price += formatDecimal(item.price*item.qty);
            cost += formatDecimal(item.cost * item.qty);
        });
        $('#cost').val(cost);
        return true;

    } <
    ?
    php
    if ($this - > input - > post('type') == 'combo') {
        $c = sizeof($_POST['combo_item_code']);
        $items = array();
        for ($r = 0; $r <= $c; $r++) {
            if (isset($_POST['combo_item_code'][$r]) && isset($_POST['combo_item_quantity'][$r])) {
                $items[] = array('id' => $_POST['combo_item_id'][$r], 'row' => array('id' => $_POST[
                        'combo_item_id'][$r], 'name' => $_POST['combo_item_name'][$r], 'code' => $_POST[
                        'combo_item_code'][$r], 'qty' => $_POST['combo_item_quantity'][$r], 'cost' =>
                    $_POST['combo_item_cost'][$r]));
            }
        }
        echo '
        var ci = '.json_encode($items).';
        $.each(ci, function() {
            add_product_item(this);
        });
        ';
    }
    if ($this - > input - > post('type')) {
        ?
        >
        var type = '<?= $this->input->post('
        type '); ?>';
        if (type == 'combo') {
            $('#st').slideUp();
            $('#ct').slideDown();
            //$('#cost').attr('readonly', true);
        } else if (type == 'service') {
            $('#st').slideUp();
            $('#ct').slideUp();
            //$('#cost').attr('readonly', false);
        } else {
            $('#ct').slideUp();
            $('#st').slideDown();
            //$('#cost').attr('readonly', false);
        }

        <
        ?
        php
    } ?
    >
});
</script>