<?php $r="../";
require_once($r."inc/funciones.php");
validNotSession($r);
$mysqli = connectDB($r);
$_GET['error'];
$_GET['msn'];
$code = $_GET['code'];
$infocotizacion = sinfo('z_cotizacion',$code);
$spe=$_SESSION['perfil'];
roleaccess(1810);
?>
<!DOCTYPE html>
<html lang="es">
  <?php include $r."inc/head.php"; ?>
  <? if($wa!=''){ ?><script>
      window.open("pagina.html","miventana","width=300,height=200,menubar=no")
  </script>
  <? } ?>
<script type="text/javascript">
function EliminarFila(menos,id) {
    var n = id.toString();
    idx = array.indexOf(n);
    array.splice(idx, 1);
    console.log(array);
    $("#trow" + id).remove();
    loadretica();
    
}

</script>
<body class="fixed-nav sidenav-toggled sticky-footer bg-dark" id="page-top">
  <div class="content-wrapper">
    <div class="container-fluid">
      <?php include $r."inc/nav.php"; ?>
      <h4>COTIZACIÓN</h4>
      <form id="formulario" class="preforma" name="preforma" method="post" action="acciones/editcot.php">
          <input type="hidden" name="preforma" value="<?= $code; ?>">
        <div class="form-group row">
          <label class="col-sm-2 col-form-label">Cliente</label>
          <div class="col-sm-8">
              <select data-placeholder="Seleccionar Cliente" class="chosen-select" name="cliente" onchange="otro(this.value)">
                    <option value="otro">Otro</option>
                    <? $resultado = $mysqli->query("SELECT * FROM z_clientes WHERE eliminado=0 ORDER BY nombre ASC");
                  while ($fila = $resultado->fetch_assoc()){?><option value="<?= $fila["id"]; ?>" <? if($fila["id"]==$infocotizacion['idcliente']){ ?>selected<? } ?>><?= $fila["nombre"] ?></option><? } ?>
              </select>
          </div>
        </div>
            <div class="row">
              <div id="otro" class="col-md-6 <? if($infocotizacion['idcliente']){ ?>d-none<? } ?>">
                  <div class="form-group row">
                    <label for="Empresa" class="col-sm-2 col-form-label">Empresa</label>
                    <div class="col-sm-10">
                      <input type="text" name="empresa" class="form-control" placeholder="Nombre Empresa" value="<?= $infocotizacion['empresa']; ?>">
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="contacto" class="col-sm-2 col-form-label">Contacto</label>
                    <div class="col-sm-10">
                      <input type="text" name="contacto" class="form-control" id="contacto" placeholder="Nombre del Contacto" value="<?= $infocotizacion['contacto']; ?>">
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="celular" class="col-sm-2 col-form-label">Celular</label>
                    <div class="col-sm-10">
                      <input type="number" name="celular" class="form-control" id="celular" placeholder="Numero del Contacto" value="<?= $infocotizacion['telefono']; ?>">
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="ciudad" class="col-sm-2 col-form-label">Ciudad</label>
                    <div class="col-sm-10">
                        <select class="chosen-select" name="ciudad" id="ciudad">
                        <? $resultado = $mysqli->query("SELECT * FROM `z_municipios` ORDER BY `departamento` ASC");
                        while ($fila = $resultado->fetch_assoc()){ $infodepa = info('departamento','z_departamentos',$fila["departamento"]);?> <option value="<?= $fila["id"]; ?>" <? if($fila["id"]==$infocotizacion['ciudad']){ ?> selected<? } ?>><?= $fila["municipio"].' - '.$infodepa['departamento']; ?></option>
                        <? } ?>
                    </select>
                      
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="correo" class="col-sm-2 col-form-label">Correo Electronico</label>
                    <div class="col-sm-10">
                      <input type="email" name="correo" class="form-control" id="correo" placeholder="Correo del Contacto"  value="<?= $infocotizacion['correo']; ?>">
                    </div>
                  </div>
              </div>
              <div class="col-md-6">
                  <div class="form-group">
                    <label for="pago">Pago</label>
                    <select name="pago" class="form-control" name="pago" id="pago">
                        <? $resultado = $mysqli->query("SELECT * FROM `z_pagos_medios` ORDER BY id ASC");
                        while ($fila = $resultado->fetch_assoc()){ ?><option value="<?=$fila["id"]; ?>" <? if($fila["id"]==$infocotizacion['idpago']){ ?> selected<? } ?>><?=$fila["medio"]; ?></option><? } ?>
                    </select>
                  </div>
                  <div class="form-group">
                    <label for="documentos">Documentos</label>
                    <textarea name="documentos" readonly class="form-control" id="documentos" placeholder="Documentos requeridos"><?= $infocotizacion['documentos']; ?></textarea>
                  </div>
              </div>
          </div>
        <hr/>
      <a id="btnagregar" class="btn btn-primary btn-block text-white" data-toggle="modal" data-target="#exampleModal"><i class="fa fa-plus"></i> Agregar</a>
      <hr/>
      <style>
          /*.citizainput{
            border:none;
            color: #dc3545!important;
            font-family: inherit;
            font-weight: 500;
            line-height: 1.2;
            font-size: 1rem;
            text-align: right;
            width: 150px;
          }
          .citizainput:focus-visible{
            outline:none;
          }*/
      </style>
        <table style="width:100%" class="table">
          <thead>
            <tr>
              <th>Nombre Producto</th>
              <th>Cantidad</th>
              <th>Precio</th>
              <th>Total</th>
              <th>Accion</th>
            </tr>
          </thead>
          <tfoot>
            <tr>
                <td colspan="3" class="text-right h6"><b>TOTAL BASE</b></td>
                <td class="text-danger h6">$ <span id="total"><?= number_format($infocotizacion['subtotal']); ?></span> COP</td>
                <td><input type="hidden" name="totalbase" value="<?= $infocotizacion['subtotal']; ?>"></td>
           </tr>
            <tr>
                <td colspan="3" class="text-right h6"><input type="checkbox" name="civa" checked> <b>TOTAL IVA</b></td>
                <td class="text-danger h6">$ <span id="tiva"><?= number_format($infocotizacion['tiva']); ?></span> COP</td>
                <td><input type="hidden" name="tiva" value="<?= $infocotizacion['tiva']; ?>"></td>
           </tr>
            <tr>
                <td colspan="3" class="text-right h6"><input type="checkbox" name="cica" <? if($infocotizacion['ica']>0){ ?>checked<? } ?>> <b>ICA</b></td>
                <td class="text-danger h6">$ <span id="totalica"><?= number_format($infocotizacion['ica']); ?></span> COP</td>
                <td><input type="hidden" name="totalica" value="<?= $infocotizacion['ica']; ?>"></td>
           </tr>
            <tr>
                <td colspan="3" class="text-right h6"><input type="checkbox" name="crete" <? if($infocotizacion['retefuente']>0){ ?>checked<? } ?>> <b>RETEFUENTE</b></td>
                <td class="text-danger h6">$ <span id="totalretefuente"><?= number_format($infocotizacion['retefuente']); ?></span> COP</td>
                <td><input type="hidden" name="totalretefuente" value="<?= $infocotizacion['retefuente']; ?>"></td>
           </tr>
            <tr>
                <td colspan="3" class="text-right h6"><b>TOTAL</b></td>
                <td class="text-danger h6">$ <span id="ttotal"><?= number_format($infocotizacion['total']); ?></span> COP</td>
                <td><input type="hidden" name="ttotal" value="<?= str_replace(".", "",$infocotizacion['total']); ?>"></td>
           </tr>
          </tfoot>
          <tbody id="tabla">
              <?
                $idspedido = array();
                $resultado = $mysqli->query("SELECT * FROM `z_cotizacion_pedido` WHERE `idcotizacion`=$code"); while ($fila = $resultado->fetch_assoc()){
                if($fila['idproducto']>=2147483647){
                $pcode = $fila['idproducto'].$fila['producto'].$fila['idpresentacion'];
                array_push($idspedido,$pcode);
              ?>
              <tr id="trow<?= $pcode; ?>">
                  <td><input type="hidden" value="<?= $pcode; ?>" name="iden<?= $pcode; ?>"><input type="hidden" value="<?= $fila['idproducto']; ?>" name="cod<?= $pcode; ?>"><?= decryptIt($fila['producto']); ?></td>
                  <td><input type="number" class="form-control" style="display: inline-block;width: 90px;" value="<?= $fila['cantidad']; ?>" name="cant<?= $pcode; ?>"><?= sinfo('z_presentaciones_productos',$fila['idpresentacion'])['presentacion']; ?><input type="hidden" value="<?= $fila['idpresentacion']; ?>" name="tipo<?= $pcode; ?>"></td>
                  <td><input type="number" class="form-control" style="display: inline-block;width: 122px;" value="<?= $fila['precio']; ?>" name="prec<?= $pcode; ?>">COP</td>
                  <td><input type="hidden" value="<?= $fila['iva']; ?>" name="iva<?= $pcode; ?>"><span id="sub<?= $pcode; ?>"></span></td>
                  <? $subtotal = $fila['cantidad']*$fila['precio']; ?>
                  <td><a title="Borrar" onclick="EliminarFila(<?= $subtotal; ?>,'<?= $pcode; ?>');"><i class="fa text-danger fa-trash fa-2x fa-lg"></i></a></td>
              </tr>
              <? }else{
                $pcode = $fila['idproducto'].$fila['idpresentacion'];
                array_push($idspedido,$pcode);
              ?>
              <tr id="trow<?= $pcode; ?>">
                  <td><input type="hidden" value="<?= $pcode; ?>" name="iden<?= $pcode; ?>"><input type="hidden" value="<?= $fila['idproducto']; ?>" name="cod<?= $pcode; ?>"><?= sinfo('z_productos',$fila['idproducto'])['producto']; ?></td>
                  <td><input type="number" class="form-control" style="display: inline-block;width: 90px;" value="<?= $fila['cantidad']; ?>" name="cant<?= $pcode; ?>"><?= sinfo('z_presentaciones_productos',$fila['idpresentacion'])['presentacion']; ?><input type="hidden" value="<?= $fila['idpresentacion']; ?>" name="tipo<?= $pcode; ?>"></td>
                  <td><input type="number" class="form-control" style="display: inline-block;width: 122px;" value="<?= $fila['precio']; ?>" name="prec<?= $pcode; ?>">COP</td>
                  <td><input type="hidden" value="<?= $fila['iva']; ?>" name="iva<?= $pcode; ?>"><span id="sub<?= $pcode; ?>"></span></td>
                  <? $subtotal = $fila['cantidad']*$fila['precio']; ?>
                  <td><a title="Borrar" onclick="EliminarFila(<?= $subtotal; ?>,<?= $pcode; ?>);"><i class="fa text-danger fa-trash fa-2x fa-lg"></i></a></td>
              </tr>
              <? }} ?>
          </tbody>
        </table>
        <!--<div class="form-group row">
          <label for="cliente" class="col-sm-2 col-form-label">Fecha de pago</label>
          <div class="col-sm-4"><? $fecha=date("Y-m-d"/*, strtotime("+1 days")*/); ?>
            <input type="date" class="form-control" name="fecha"  min="<?= date("Y-m-d"); ?>" value="<?= $infocotizacion['fecha_entrega']; ?>"  required>
          </div>
        </div>-->
        <div class="form-group row">
          <label for="nota" class="col-sm-2 col-form-label">Nota</label>
          <div class="col-sm-5">
            <textarea type="text" class="form-control" name="nota"><?= $infocotizacion['comentarios']; ?></textarea>
          </div>
          <label for="otros" class="col-sm-2 col-form-label">Costo adicional</label>
          <div class="col-sm-3">
            <input type="number" class="form-control" name="otros" placeholder="$ 0 COP"  value="<?= $infocotizacion['adicional']; ?>">
          </div>
        </div>
        <input type="submit" class="btn btn-primary btn-sm float-right m-1" value="Guardar Cotizacion">
        <button onclick="window.history.go(-1);" class="btn btn-danger btn-sm float-left m-1">Atras</button>
      </form>
      
                <!-- Logout Modal-->
          <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
             <div class="modal-content">
                <div id="mesage"></div>
              <div class="modal-header" style="padding-top:0px;padding-bottom:0px;">
                <h5 class="modal-title" id="exampleModalLabel">Agregar Producto</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              </div>
              
                  <style>
                      #producto_chosen{
                          width:100% !important;
                      }
                  </style>
                <div class="modal-body">
                <form id="anadir" method="post" action="pedido.php">
                  <input type="hidden" name="bod" value="0">
                  <div class="form-group row">
                    <label for="recipient-name" class="col-sm-3 col-form-label">Producto:</label>
                    <div class="col-sm-9">
                        <select data-placeholder="Seleccionar producto" class="chosen-select" name="producto" id="producto" onchange="otrop(this.value)" required>
                            <option disabled selected>Selecione producto</option>
                            <? $resultado = $mysqli->query("SELECT * FROM z_productos WHERE eliminado=0 ORDER BY producto ASC");
                            while ($fila = $resultado->fetch_assoc()){ ?><option value="<?= $fila["id"] ?>"><?= $fila["codigo"].'-'.$fila["producto"]; ?></option>
                            <? }; ?>
                            <option value="0">otro</option>
                      </select>
                    </div>
                  </div>
                  <div class="form-group row d-none" id="nproducto">
                    <label for="recipient-name" class="col-sm-3 col-form-label">Nombre:</label>
                    <div class="col-sm-9">
                        <input type="text" name="nproducto" class="form-control">
                    </div>
                  </div>
                  <div class="form-group row d-none" id="oiva">
                    <label for="recipient-name" class="col-sm-3 col-form-label">IVA:</label>
                    <div class="col-sm-9">
                        <select class="form-control" name="oiva">
                            <? for($i=0;$i<=30;$i++){ ?><option value="<?= $i; ?>"><?= $i.'%'; ?></option><? } ?>
                      </select>
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="recipient-name" class="col-sm-3 col-form-label">Presentacion:</label>
                    <div class="col-sm-9">
                        <select data-placeholder="Seleccionar present" class="chosen-select" name="present" id="present" required>
                            <option disabled selected>Selecione presentacion</option>
                            <? $resultado = $mysqli->query("SELECT * FROM z_presentaciones_productos ORDER BY presentacion");
                            while ($fila = $resultado->fetch_assoc()){?><option value="<?= $fila["id"]; ?>" <? if($fila["id"]==22){ echo 'selected';} ?>><?= $fila['presentacion']; ?></option>
                            <? }; ?>
                      </select>
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="precio" class="col-sm-3 col-form-label">Cantidad: </label>
                    <div class="col-sm-4"><input class="form-control" type="number" id="cantidad" name="cantidad" placeholder="cantidad" title="cantidad" step="0.001" value="1" required></div>
                    <div class="col-2 h6" id="unidad"></div>
                  </div>
                  <div class="form-group row">
                    <label for="cantidad" class="col-sm-3 col-form-label">precio: </label>
                    <div class="col-sm-7"><input class="form-control" type="number" id="precio" name="precio" placeholder="precio" title="precio" step="0.001" required></div>
                  </div>
                  <div class="form-group">
                    <button type="button" class="btn float-left btn-danger btn-sm" data-dismiss="modal" aria-label="Close">CERRAR</button>
                    <button type="submit" value="Enviar" class="btn float-right btn-success btn-sm">AGREGAR</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        


<!-- Modal -->
<div class="modal fade" id="modalpedido" tabindex="-1" role="dialog" aria-labelledby="modalpedidoLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalpedidoLabel">Pedido anterior<span id="code"></span></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form id="memoria">
      </form>
    </div>
  </div>
</div>
        
    </div>
  </div>
  <script>
        function otro(valor){
            if(valor === 'otro'){
                $('#otro').attr('class','col-md-6 d-block');
            }else{
                $('#otro').attr('class','d-none');
                var data = $('option[value='+valor+']').attr('attrm');
                $('#ciudad').val(data).trigger('chosen:updated');
            }
            loadretica();
        }
        
        function otrop(valor){
            if(valor == 0){
                $('#nproducto').attr('class','form-group row d-flex');
                $('#oiva').attr('class','form-group row d-flex');
                $("input[name=nproducto]").attr("required", "true");
            }else{
                $('#nproducto').attr('class','form-group row d-none');
                $('#oiva').attr('class','form-group row d-none');
                $("input[name=nproducto]").removeAttr('required');
            }
            loadretica();
        }
        function loadretica(){
            <? $resultado = $mysqli->query("SELECT base,porcentaje FROM `z_ica` ORDER BY `id` DESC"); $fila = $resultado->fetch_assoc();  ?>
            var baseica = <?= $fila['base']; ?>;
            var ica =  <?= $fila['porcentaje']; ?>;
            <? $resultado = $mysqli->query("SELECT base,porcentaje FROM `z_retefuente` ORDER BY `id` DESC"); $fila = $resultado->fetch_assoc(); ?>
            var baseretefuente = <?= $fila['base']; ?>;
            var retefuente = <?= $fila['porcentaje']; ?>;
            var municipio =  $('#ciudad').val();
            var totalcotizacion = 0;
            var tivas = 0;
            setTimeout(function(){
                 array.forEach(function (element) {
                     if(element!=0){
                         var precio = $('input[name=prec'+element+']').val();
                         var cantidad = $('input[name=cant'+element+']').val();
                         var iva = $('input[name=iva'+element+']').val();
                         $("#sub"+element).html(parseInt(precio)*parseFloat(cantidad));
                         totalcotizacion = parseInt(totalcotizacion)+(parseInt(precio)*parseFloat(cantidad));
                         if( $('input[name=civa]').prop('checked') ) {
                             var sumiva = (parseInt(precio)*parseFloat(cantidad)*parseInt(iva))/100;
                            tivas = parseInt(tivas) + parseInt(sumiva);
                         }else{
                             tivas = 0;
                         }
                     }
                 });
                var subtotal= parseInt(totalcotizacion) + parseInt(tivas);
                 if( $('input[name=cica]').prop('checked') ) {
                    if(municipio=='107'){
                        if(totalcotizacion>=baseica){
                            var totalica = Math.round(totalcotizacion * ica)/100;
                            console.log(totalcotizacion+' - '+ica+' - '+totalica);
                            $('#totalica').html(totalica.toLocaleString('en-US'));
                        }else{
                            $('#totalica').html(0);
                            var totalica = 0;
                        }
                    }else{
                        $('#totalica').html(0);
                        var totalica = 0;
                    }
                }else{
                    $('#totalica').html(0);
                    var totalica = 0;
                }
                if( $('input[name=crete]').prop('checked') ) {
                    if(totalcotizacion>=baseretefuente){
                        var totalrete = Math.round(totalcotizacion * retefuente)/100;
                        $('#totalretefuente').html(totalrete.toLocaleString('en-US'));
                    }else{
                        $('#totalretefuente').html(0);
                        var totalrete = 0;
                    }
                }else{
                    $('#totalretefuente').html(0);
                    var totalrete = 0;
                }
                var ttotal = parseInt(totalcotizacion)+parseInt(tivas)-parseInt(totalica)-parseInt(totalrete);
                $('input[name=totalbase]').val(totalcotizacion);
                $('input[name=totalica]').val(totalica);
                $('input[name=totalretefuente]').val(totalrete);
                $('input[name=ttotal]').val(ttotal);
                $('input[name=tiva]').val(tivas);
                $('#ttotal').html(ttotal.toLocaleString('en-US'));
                $('#tiva').html(tivas.toLocaleString('en-US'));
                $("#total").html(totalcotizacion);
            }, 500);
        }
    </script>
    <?php include $r."inc/foot.php"; ?>
    <script>
        $('input[type=number]').on('keyup', loadretica);
        $('input[name="civa"], input[name=cica], input[name=crete]').on('change', loadretica);
        $('#ciudad').on('change', loadretica);
        $('#exampleModal').on('hidden.bs.modal', loadretica);
        
  </script>
  <script>
    var array = ['0'<? foreach ($idspedido as $value) {    echo ",'$value'";}?>];
    var total = <?= $infocotizacion['subtotal']; ?>;
    </script>
</body>
</html>