<?php $r="../";
require_once($r."inc/funciones.php");
$titlepage = "Editar Orden de Compra";
validNotSession($r);
$mysqli = connectDB($r);
$_GET['error'];
$_GET['msn'];
$spe=$_SESSION['perfil'];
$idcompra=$_GET['id'];
roleaccess(1920);
$infoorden = sinfo('z_orden_compra',$idcompra);
$infoproveedor = sinfo('z_proveedores',$idcompra['idproveedor']);
?>

  <?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);
    console.log(idx);
    array.splice(idx, 1);
    $("#tabla").append('<input type="hidden" name="eliminar[]" value="'+id+'">');
    $("#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>Orden de Compra</h4>
      <form id="formulario" class="pedido" name="pedido" method="post" action="acciones_editar.php">
          <input type="hidden" name="editar" value="<?= $infoorden['id']; ?>">
        <div class="form-group row">
          <label class="col-sm-2 col-form-label">Proveedores </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>
                    <? $sqlproveedores = $mysqli->query("SELECT * FROM `z_proveedores`"); $selected ='';
                        while($rowproveedor = $sqlproveedores->fetch_assoc()){ ?>
                      
                      <option value="<?= $rowproveedor["id"]; ?>" <? if($rowproveedor["id"] === $infoorden['idproveedor']){ echo 'selected'; } ?> > <?= $rowproveedor["nombre"]; ?></option>';
                  
                    <? } ?>
              </select>
          </div>
        </div>
            <div class="row">
              <div id="otro" <?  if($infoorden['idproveedor']!=NULL){ $display = 'd-none'; } ?> class="col-md-6 <?= $display; ?>" >
                  <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="<?= $infoorden['proveedor']; ?>">
                    </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="<?= $infoorden['asesor']; ?>">
                    </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="<?= $infoproveedor['celular1']; ?>">
                    </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">
                        <?  $sqlmunicipios = $mysqli->query("SELECT * FROM `z_municipios` ORDER BY `departamento` ASC");
                        while ($rowmunicipio = $sqlmunicipios->fetch_assoc()){  
                            $infodepa = info('departamento','z_departamentos',$rowmunicipio["departamento"]); ?> 
                            <option value="<?= $rowmunicipio["id"]; ?>" <? if($infoproveedor['idmunicipio']==$rowmunicipio["id"]){ echo 'selected'; } ?>><?= $rowmunicipio["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="<?= $infoorden['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()){ $selected = ''; if($infoorden['idpago']==$fila["id"]){ $selected = 'selected'; } echo "<option value='{$fila['íd']}' $selected> {$fila['medio']}</option>";
                    } ?>
                    </select>
                  </div>
                  <div class="form-group">
                    <label for="documentos">Documentos</label>
                    <textarea name="documentos" class="form-control" id="documentos" placeholder="Documentos requeridos"><?= $infoorden['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/>
        <table style="width:100%" class="table">
          <thead>
            <tr>
              <th>Nombre Producto</th>
              <th>presentacion</th>
              <th>Cantidad</th>
              <th>Precio</th>
              <th>Total</th>
              <th>Accion</th>
            </tr>
          </thead>
          <tfoot>
            <tr>
                <td colspan="4" class="text-right h6"><b>TOTAL BASE</b></td>
                <td class="text-danger h6">$ <span id="total">0</span> COP</td>
                <td><input type="hidden" name="totalbase"></td>
           </tr>
            <tr>
                <td colspan="4" class="text-right h6"><input type="checkbox" name="civa" <? if($infoorden['tiva']){ echo 'checked'; }?>> <b>TOTAL IVA</b></td>
                <td class="text-danger h6">$ <span id="tiva">0</span> COP</td>
                <td><input type="hidden" name="tiva"></td>
           </tr>
            <tr>
                <td colspan="4" class="text-right h6"><input type="checkbox" name="cica" <? if($infoorden['ica']){ echo 'checked'; }?>> <b>ICA</b></td>
                <td class="text-danger h6">$ <span id="totalica">0</span> COP</td>
                <td><input type="hidden" name="totalica"></td>
           </tr>
            <tr>
                <td colspan="4" class="text-right h6"><input type="checkbox" name="crete" <? if($infoorden['retefuente']){ echo 'checked'; }?>> <b>RETEFUENTE</b></td>
                <td class="text-danger h6">$ <span id="totalretefuente">0</span> COP</td>
                <td><input type="hidden" name="totalretefuente"></td>
           </tr>
            <tr>
                <td colspan="4" class="text-right h6"><b>TOTAL</b></td>
                <td class="text-danger h6">$ <span id="ttotal">0</span> COP</td> 
                <td><input type="hidden" name="ttotal"></td>
           </tr>
          </tfoot>
          <tbody id="tabla">
              
               <? 
                $idspedido = array(); 
                $resultado = $mysqli->query("SELECT * FROM `z_orden_compra_pedido` WHERE `idordencompra`=$idcompra AND eliminado=0"); while ($fila = $resultado->fetch_assoc()){ array_push($idspedido,$fila['id']); $preciomasiva = $fila['precio'] * (1 + $fila['iva'] / 100);?>
                <tr id="trow<?= $fila['id']; ?>">
                    <td><input type="hidden" value="<?= $fila['id']; ?>" name="pro[<?= $fila['id']; ?>]"><?= $fila['producto']; ?></td>
                    <td><input type="hidden" value="<?= $fila['id']; ?>" name="iden<?= $fila['id']; ?>"><?= $fila['presentacion']; ?></td>
                    <td><input class="form-control" type="number" name="cant<?= $fila['id']; ?>" value="<?= $fila['cantidad']; ?>"></td>
                    <td><input class="form-control" type="hidden" name="prec<?= $fila['id']; ?>" value="<?= $fila['precio']; ?>"><input class="form-control" type="number" name="precs<?= $fila['id']; ?>" step="0.001" value="<?= $preciomasiva; ?>"></td>
                    <td><input type="hidden" value="<?= $fila['iva']; ?>" name="iva<?= $fila['id']; ?>"><span id="sub<?= $fila['id']; ?>"><?= $fila['cantidad']*$fila['precio']; ?></span></td>
                    <td><a title="Borrar" onclick="EliminarFila(<?= $fila['cantidad']*$fila['precio']; ?>,<?= $fila['id']; ?>);"><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="<?= date("Y-m-d"); ?>"  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"></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">
          </div>
        </div>
        <input type="submit" class="btn btn-success btn-sm btn-block" value="ACTUALIZAR ORDEN DE COMPRA">
      </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>
        <div class="modal-body">
        <form id="formplus">
          <div class="form-group row">
            <label for="recipient-name" class="col-sm-3 col-form-label">Producto:</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" id="addproducto" required>
            </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">
                <input class="form-control" type="text" id="addpresent" required>
            </div>
          </div>
          <div class="form-group row">
            <label for="precio" class="col-sm-3 col-form-label">Cantidad: </label>
            <div class="col-sm-9">
                <input class="form-control" type="number" id="addcantidad" step="0.001" required>
            </div>
          </div>
          <div class="form-group row">
            <label for="iva" class="col-sm-3 col-form-label">iva: </label>
            <div class="col-sm-9">
                <input class="form-control" type="number" min="0" max="99" id="addiva" value="19" required>
            </div>
          </div>
          <div class="form-group row">
            <label for="cantidad" class="col-sm-3 col-form-label">precio: </label>
            <div class="col-sm-9">
                <input class="form-control" type="number" id="addprecio" step="0.001" required>
            </div>
          </div>
          <div id="msn-alert"></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>
        

    </div>
  </div>
  <script>
     // Formulario Jovenes
   
        function otro(valor){
            if(valor === 'otro'){
                $('#otro').attr('class','col-md-6 d-block');
            }else{
                $('#otro').attr('class','d-none');
                $.post( "info.php", { infocliente: valor}).done(function( data ){ $('#ciudad').val(data).trigger('chosen:updated'); });
            }
            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']; ?>;
            
            let municipio =  parseInt($('select[name=ciudad]').val(), 10);
            var totalcotizacion = 0;
            var tivas = 0;
            setTimeout(function(){
                 array.forEach(function (element) {
                    if (element != 0) {
                        var precio = parseFloat($('input[name=precs' + element + ']').val());
                        var cantidad = parseFloat($('input[name=cant' + element + ']').val());
                        var iva = parseFloat($('input[name=iva' + element + ']').val());

                        // Calcular el precio sin IVA con más precisión
                        let preciosiniva = precio / (1 + (iva / 100));
                        preciosiniva = Math.round(preciosiniva * 100) / 100;
                        $('input[name=prec' + element + ']').val(preciosiniva);
                            
                        // Calcular subtotal y sumarlo al total de la cotización
                        var subtotal = preciosiniva * cantidad;
                        $('#sub' + element).html(moneda(subtotal));
                        totalcotizacion = parseFloat(totalcotizacion) + subtotal;
                
                        // Calcular el IVA si está activado
                        if ($('input[name=civa]').prop('checked')) {
                            var sumiva = (subtotal * iva) / 100;
                            tivas = parseFloat(tivas) + sumiva;
                        } else {
                            tivas = 0;
                        }
                    }
                });
                
                // Redondear hacia arriba el total de la cotización y el total de IVA
                totalcotizacion =totalcotizacion.toFixed(0);
                tivas = tivas.toFixed(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);
            }, 700);
        }
    </script>
    <?php include $r."inc/foot.php"; ?>
    <script>
        $('#ciudad').on('change', function(){
           loadretica(); 
        });
        $('#exampleModal').on('hidden.bs.modal', function () {
            loadretica();
        });
         $('#formplus').submit(function(event) {
            event.preventDefault();
            var id = new Date().getTime();
            var pro = $('#addproducto').val();
            var pres = $('#addpresent').val();
            var can = $('#addcantidad').val();
            let pre = parseFloat($('#addprecio').val());
            let iva = parseFloat($('#addiva').val());
            

            // Calcular el precio sin IVA con más precisión
            let preciosiniva = pre / (1 + (iva / 100));
            preciosiniva = Math.round(preciosiniva * 100) / 100;
            var subtotal = can*pre;
            array.push(''+id+'');
            var tr_str = '<tr id="trow'+id+'">' +
                        '<td><input type="hidden" value="' + pro + '" name="iden'+id+'"/>' + pro + '('+pres+')</td>' +
                        '<td><input type="hidden" value="' + pres + '" name="pres'+id+'"/>'+pres+'</td>' +
                        '<td><input type="hidden" value="' + can + '" name="cant'+id+'"/>' + can + '</td>' +
                        '<td><input  type="hidden" value="' + preciosiniva + '" name="prec'+id+'"/>' + pre + '</td>' +
                        '<td><input type="hidden" value="' + iva + '" name="iva'+id+'"/>' + subtotal + '</td>' +
                        '<td><a  title="Borrar" onclick="EliminarFila('+ subtotal + ',' + id + ');"><i class="fa text-danger fa-trash fa-2x fa-lg"></i></a></td>' +
                        '</tr>';
                        
                        total = total+subtotal;
                        $("#tabla").append(tr_str);
            
            $('#addproducto').val('');
            $('#addpresent').val('');
            $('#addcantidad').val('');
            $('#addprecio').val('');
            $('#addiva').val('');            
            loadretica();
        });
  </script>
    <script>
        $('input[type=number]').on('keyup', loadretica);
        $('input[type=number], input[name="civa"], input[name=cica], input[name=crete]').on('change', loadretica);
        $('#ciudad').on('change', loadretica);
        $('#exampleModal').on('hidden.bs.modal', loadretica);
        loadretica();
                
        
    var array = ['0'<? foreach ($idspedido as $value) {    echo ",'$value'";}?>];
    var total = <?= $infoorden['subtotal']; ?>;
  </script>
</body>
</html>