<?php
include_once '../bd/funcoes.inc';
include_once '../auxiliar/parametros.inc';
include_once '../bd/bd_produtos.inc';
include_once '../bd/bd_config_interno.php';
include_once '../bd/bd_os.inc';
include '../idiomas/config.inc';


$p_numitem = recebevar("numitem");
$p_codigo = recebevar("codigo");
$p_descricao = recebevar("descricao");
$p_qtde = recebevar("qtde");
setcookie("qtdeitem", $p_qtde, 0, '/'); // seta a qtde no cookie pra qdo
//passar pra pag de validar os campos ter o valor original da
$p_unitario = recebevar("unitario");
$p_desc = recebevar("desc");
$p_codpro = recebevar("codpro");
$path = "../html/alteraitem.php?numitem=$p_numitem*_*codigo=$p_codigo*_*descricao=$p_descricao*_*qtde=$p_qtde*_*unitario=$p_unitario*_*desc=$p_desc*_*codpro=$p_codpro";
$codos = lecookie('codos');
$codprodtabela = TrazValorCampo('os', 'npreco', 'codos', $codos);
$codmarca = TrazValorCampo('produtos', 'codmar', 'codpro', $p_codpro);
$codloja =  TrazValorCampo('os', 'codloja', 'codos', $codos);
$bloqueiaprecomarca = TrazValorCampo('marcas', 'naoalteraprecoafv', 'codmar', $codmarca);
$permite_editar_preco = ((lecookie("osmudaprecoprod") == "1") && ($bloqueiaprecomarca == 0));


if ($p_preco_minimo_sobre_venda == 1) {
  $precoMinimo = getPrecoMinimo($p_codpro, $codprodtabela);

  $margem = (1 - ($precoMinimo / $p_unitario)) * 100;

  $margemFormatada = number_format($margem, 2, ',', '.');
  $margemClass = $margem < 0 ? 'text-red' : 'text-green';
}
$habilitaDescontoPorQuantidade = habilitaDescontoPorQuantidade();
$precosPorQtd = array();

if($habilitaDescontoPorQuantidade) {
  $precosPorQtd = getPrecosPorQuantidade($p_codpro, $codprodtabela);
}

$item = getOsItem($codos, $p_numitem);
?>


<!DOCTYPE html>
<html>

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AFV 2 | <?php echo $h_title; ?></title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <!-- Bootstrap 3.3.7 -->
  <link rel="stylesheet" href="./../web/bower_components/bootstrap/dist/css/bootstrap.min.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="./../web/bower_components/font-awesome/css/font-awesome.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="./../web/bower_components/Ionicons/css/ionicons.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="./../web/dist/css/AdminLTE.min.css">
  <!-- AdminLTE Skins. Choose a skin from the css/skins
       folder instead of downloading all of them to reduce the load. -->
  <link rel="stylesheet" href="./../web/dist/css/skins/_all-skins.min.css">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->

  <!-- Google Font -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>

<body class="hold-transition skin-blue sidebar-mini">
  <!-- Site wrapper -->
  <div class="wrapper">

    <header class="main-header">
      <!-- Logo -->
      <a href="../html/cadastro.php" class="logo">
        <!-- mini logo for sidebar mini 50x50 pixels -->
        <span class="logo-mini"><b>A</b>ADV</span>
        <!-- logo for regular state and mobile devices -->
        <span class="logo-lg"><b>AFV</b> - ADV Tecnologia </span>
      </a>
      <!-- Header Navbar: style can be found in header.less -->
      <nav class="navbar navbar-static-top">
        <!-- Sidebar toggle button-->
        <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </a>
      </nav>
    </header>










    <!-- =============================================== -->
    <!-- Inserir modal aqui-->
    <div class="modal fade" id="modal-default">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title"><?php echo $m_relatorios; ?></h4>
          </div>
          <div class="modal-body">
            <p>
              <?php
              include './../html/relatorios.php';
              ?>
            </p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default pull-left" data-dismiss="modal"><?php echo $bt_sair; ?></button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <!-- /.modal -->






    <!-- -->
    <div class="modal fade" id="modal-buscarcliente">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title"><?php echo $b_busca_cliente_nova_venda; ?></h4>
          </div>
          <div class="modal-body">


            <form action="../php/buscacli.php" method="post" name="procuracadastro" id="procuracadastro">

              <div class="box-body">
                <div class="form-group">
                  <label for="Razao"><?php echo $b_razao_social; ?></label>
                  <input name="razao" class="form-control" id="razao" placeholder="<?php echo $b_buscar_cliente; ?>" type="text">
                </div>



                <script>
                  document.procuracadastro.razao.focus();
                </script>
              </div>

          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default pull-left" data-dismiss="modal"><?php echo $bt_sair; ?></button>
            <input type="submit" class="btn btn-primary pull-right" name="Enviar" value="<?php echo $bt_localizar; ?>" alt='Localizar' />
          </div>
          </form>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <!-- /.modal -->



    <!-- Fim do modal -->

    <!-- Left side column. contains the sidebar -->
    <aside class="main-sidebar">
      <!-- sidebar: style can be found in sidebar.less -->
      <section class="sidebar">
        <!-- Sidebar user panel -->
        <div class="user-panel">
          <div class="pull-left image">
            <img src="./../icons/frame.png" class="img-circle" alt="User Image">
          </div>
          <div class="pull-left info">
            <p name="usuariologado">
              <?php
              include_once '../bd/funcoes.inc';
              $p_codusu = lecookie("codusu");
              echo (TrazValorCampo('senhas', 'usuario', 'codusu', lecookie('codusu')));
              ?>
            </p>
          </div>
        </div>

        <!-- sidebar menu: : style can be found in sidebar.less -->
        <ul class="sidebar-menu" data-widget="tree">
          <li class="header"><?php echo $g_painel_navegacao; ?></li>
          <li class="treeview">
            <a href="#">
              <i class="fa fa-dashboard"></i> <span name='MVendas'><?php echo $m_vendas; ?></span>
              <span class="pull-right-container">
                <i class="fa fa-angle-left pull-right"></i>
              </span>
            </a>
            <ul class="treeview-menu">
              <li><a href="./buscahistvnd.php" name='HistVenda'><i class="fa fa-circle-o"></i><?php echo $m_historico_venda; ?> </a></li>
              <li><a href="#" data-toggle="modal" data-target="#modal-buscarcliente" name='NovaVenda'><i class="fa fa-circle-o"></i><?php echo $m_nova_venda; ?> </a></li>
            </ul>
          </li>
          <li class="treeview">
            <a href="#">
              <i class="glyphicon glyphicon-user"></i> <span name='MClientes'><?php echo $m_clientes; ?></span>
              <span class="pull-right-container">
                <i class="fa fa-angle-left pull-right"></i>
              </span>
            </a>
            <ul class="treeview-menu">
              <li><a href="./cadastronovo.php"><i class="fa fa-circle-o"></i><?php echo $m_cadastrar_cliente; ?> </a></li>
              <li>
                <a href="#" data-toggle="modal" data-target="#modal-buscarcliente" name='MLocalizarCliente'>
                  <i class="fa fa-circle-o"></i>
                  <?php echo $m_localizar_cliente; ?> </a>
              </li>
            </ul>
          </li>
          <li class="treeview">
            <a href="#" data-toggle="modal" data-target="#modal-default">
              <i class="fa fa-files-o"></i>
              <span><?php echo $m_relatorios; ?> </span>
            </a>
          </li>
          <li>
            <a href="./produtos_consulta.php">
              <i class="glyphicon glyphicon-search"></i> <span><?php echo $m_consulta_produtos; ?> </span>
            </a>
          </li>
          <li>
            <a href="../php/logoff.php">
              <i class="glyphicon glyphicon-off"></i>
              <span name='logout'><?php echo $m_Logout; ?> </span>
            </a>
          </li>
        </ul>
      </section>
      <!-- /.sidebar -->
    </aside>

    <!-- =============================================== -->

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
      <section class="content-header">
        <h1>

        <?php echo $h_title; ?>
        </h1>
        <ol class="breadcrumb">
          <!-- controle de paginas aqui-->
          <li><a href="#"><i class="fa fa-dashboard"></i><?php echo $g_inicio; ?> </a></li>
        </ol>
      </section>

      <!-- Main content -->
      <section class="content">

        <!-- Default box -->
        <div class="box">
          <div class="box-header with-border">
            <h3 class="box-title"><?php echo $b_produto; echo $p_descricao; ?></h3>

            <div class="box-tools pull-right">
              <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
                <i class="fa fa-minus"></i></button>
              <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
                <i class="fa fa-times"></i></button>
            </div>
          </div>
          <div class="box-body">

            <div class="alteraitem">

              <form name="selprodutos" action="../php/alteraitemos.php" id="formAlteraProduto">
                <input name="numitem" type="hidden" value="<?php echo $p_numitem ?>" />
                <input name="codpro" type="hidden" value="<?php echo $p_codpro ?>" />
                <input name="path" type="hidden" value="<?php echo $path ?>" />



                <div class="form-group">
                  <label>
                  <?php echo $b_codigo; echo $p_codigo; ?><BR>
                  </label>
                </div>

                <div class="form-group">
                  <?php BuscaLotes($codos,$p_codpro, $p_numitem, $codloja);?>
                </div>


                <div class="form-group">
                  <label>
                  <?php  echo $b_qtde .": " ; echo $p_qtde; ?>
                  </label>



                  <input name="qtde" type="text" size="6" class="form-control input-decimal" id="qtdItems" value="<?php echo $p_qtde ?>" />
                  
                  
                  <input class='preco-por-qtde' qtde-base=true name='precobase' type='hidden' value="<?php echo $item["precobase"]?>" />
                    
                  
                  <?php if($habilitaDescontoPorQuantidade):?>

                    <input class='preco-por-qtde' qtde-base=true name='preco-por-qtde-base' type='hidden' value="<?php echo number_format($item["precobase"], 2, '.', '')?>" />
                    
                    <?php foreach ($precosPorQtd as $index => $ppq):
                        $precoAlternativoPorQtde = $ppq["valor"];
                        $qtdeini = $ppq["qtdeini"];
                        $qtdefim = $ppq["qtdefim"];
                      ?>
                        <input class='preco-por-qtde' name='preco-por-qtde' type='hidden' qtd-from=<?php echo $qtdeini; ?> qtd-to=<?php echo $qtdefim ?> value="<?php echo number_format($precoAlternativoPorQtde, 2, '.', '') ?> " />
                    <?php endforeach;?>
                  <?php endif;?>
                </div>

                <div class="form-group">
                  <label>
                  <?php echo $b_preco; ?> <?php echo number_format($p_unitario, 2, ',', '.') ?>
                  </label>
                  <?php if ($permite_editar_preco) : ?>                    
                    <input name="unitario" class="form-control input-decimal" id="inputPreco" type="text" size="6" value="<?php echo $p_unitario ?>" /> <br />
                  <?php else : ?>
                    <input name="unitario" type="hidden" value="<?php echo $p_unitario ?>" />                                     
                  <?php endif; ?>
                  <?php if ($p_preco_minimo_sobre_venda ==  1) : ?>
                    <label>
                    <?php echo $b_preco_minimo; ?> <?php echo number_format($precoMinimo, 2, ',', '.') ?>
                    </label>
                    <br>
                    <label>
                    <?php echo $b_margem; ?> <span class="<?php echo $margemClass ?>"> <?php echo $margemFormatada ?>% </span>
                    </label>
                  <?php endif; ?>
                </div>


                
                
                  <div class="form-group">

                    <label for='Enviar' id='Enviar'><?php echo $b_desconto; ?></label>

                    <div style="display: flex;">
                      <div style="display: inline-block;">
                        <div class="form-group">
                          <label>
                            <input type="radio" name="tipoDesconto" id="tipoDesconto1" value="absoluto">
                            R$
                          </label>

                          &nbsp;&nbsp;
                          <label>
                            <input type="radio" name="tipoDesconto" id="tipoDesconto2" value="percentual" checked="">
                            %
                          </label>

                        </div>
                      </div>
                    

                      &nbsp;&nbsp;


                      <div style="display: inline-block;margin-left: 15px;">
                        <div class='input-group input-group-sm'>
                          <input class='form-control input-decimal' type='text' name='desc' value="<?php if (!$p_aplicdescpreco) { echo $p_desc; } ?>"
                                  id="inputDesconto" />
                        </div>
                      </div>
                    </div>



                 </div>

                




                <div class="form-group">
                  <label for=""><?php echo $b_observacao_item; ?> </label>
                  <textarea name="obsItem" class="form-control" cols="30" rows="1"><?php echo $item['obs'] ?></textarea>
                </div>

                
                <a href='../html/produtos_consulta.php' class="btn btn-primary">
                <?php echo $bt_voltar; ?> 
                </a>


                <input type='submit' name='Enviar' id='Enviar' value="<?php echo $bt_salvar; ?>" alt='Salvar' class="btn btn-success" onclick="return checkForm()" />

              </form>
            </div>

            <script>
              document.selprodutos.desc.focus();
            </script>


<script>
    function checkForm() {
        
      if (document.getElementById("qtdelotes") != null){

        var qtdelotes = parseFloat(document.getElementById("qtdelotes").value);
        var qtdeitemgeral = parseFloat(document.getElementById("qtdItems").value); 
        var totalizador = 0.00;
        var indexstr = '';
        

      
        for (var i = 0; i < qtdelotes; i++) {
          indexstr = String(i);
          totalizador = totalizador + parseFloat(document.getElementById("qtdeusada"+indexstr).value) ;
        };
      
        if (totalizador != qtdeitemgeral){
          alert("A soma das quantidades de lotes deve ser igual a quantidade total do item");
          return false;
        }
      } 
          
          
    }
</script>






























            <!-- Finalizar aqui-->
          </div>

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

      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <?php  include_once '../html/footer.php'; ?>
  </div>
  <!-- ./wrapper -->

  <!-- jQuery 3 -->
  <script src="../web/bower_components/jquery/dist/jquery.min.js"></script>
  <!-- Bootstrap 3.3.7 -->
  <script src="../web/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
  <!-- SlimScroll -->
  <script src="../web/bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
  <!-- FastClick -->
  <script src="../web/bower_components/fastclick/lib/fastclick.js"></script>
  <!-- AdminLTE App -->
  <script src="../web/dist/js/adminlte.min.js"></script>
  <!-- AdminLTE for demo purposes -->
  <script src="../web/dist/js/demo.js"></script>
  <script>
    $(document).ready(function() {
      $('.sidebar-menu').tree();



      $("#qtdItems").change(function(evt){
            var elm = evt.target;
            var val = parseFloat(elm.value.replace(/\./g, "").replace(/\,/g, "."));
            var qtd = isNaN(val) || val === "" ? 0 : val;
            alteraPrecoPorQtde(qtd);
        })

      var maskNumber = function(val) {

        var digitos = val.match(/\d/g);
        if (!digitos)
          digitos = [];

        while (digitos.length < 3) {
          digitos.unshift(0)
        }
        var decimals = [];
        decimals.unshift(digitos.pop());
        decimals.unshift(digitos.pop());

        while (digitos.length > 1 && digitos[0] == 0) {
          digitos.shift()
        }

        var digitosFormated = [];
        digitos.reverse().forEach(function(d, index) {
          if (index % 3 == 0 && index != 0)
            digitosFormated.unshift('.');
          digitosFormated.unshift(d);
        })

        return digitosFormated.join("") + "," + decimals.join("");
      };

      var $inputDecimal = $(".input-decimal");
      $inputDecimal.keyup(function(evt) {
        var el = $(evt.target);
        var val = el.val();
        masked = maskNumber(val);
        el.val(masked)
      });

      $inputDecimal.each(function() {
        var $this = $(this);
        $this.val(
          maskNumber($this.val())
        );
      });


      $("#formAlteraProduto").submit(function(evt) {
        $inputDecimal.each(function() {
          var $this = $(this);
          var val = $this.val();
          var valSplit = val.split(",");
          var decimals = valSplit[1];
          var integer = valSplit[0];
          var sanitizedValue = integer.replace(/\./g, "") + "." + decimals;
          $this.val(sanitizedValue);
        })
      })


      <?php if($habilitaDescontoPorQuantidade):?>
                function alteraPrecoPorQtde(qtd) {
                    var options = $(".preco-por-qtde").map(function (index, inpt){ 
                            var isBase = inpt.getAttribute("qtde-base");
                            var from = parseInt(inpt.getAttribute("qtd-from"));
                            var to = parseInt(inpt.getAttribute("qtd-to"));
                            var value = inpt.value;
                            return { 
                                isBase,
                                from,
                                to,
                                value
                            }
                        }).toArray();
                        var precoPorQtde = 
                            options
                                .find(function(opt){ return qtd >= opt.from && qtd <= opt.to })
                            || options
                                .find(function(opt){ return opt.isBase == "true" })
                            ;

                        $("#inputPreco")
                            .val(precoPorQtde.value)
                            .trigger("keyup");
                }
            <?php endif;?>


    });
  </script>
</body>

</html>