<?php
header("Content-Type: text/html; charset=UTF-8");
$r="../";
require_once($r."inc/funciones.php");
$titlepage = "Nueva Pedido";
validNotSession($r);
$mysqli = connectDB($r);
$mysqli->set_charset("utf8");
$_GET['error'];
$_GET['msn'];
$spe=$_SESSION['perfil'];
roleaccess(1460);

// 1. Validar existencia del parámetro 'reference'
if (!isset($_GET['reference']) || empty($_GET['reference'])) {
    header("Location: pagina_no_valida.php");
    exit();
}

$reference = $mysqli->real_escape_string($_GET['reference']);

// 2. Verificar si hay items con ese idpedido en la tabla de items
$consulta_items = $mysqli->query("SELECT * FROM pagina_compras_mails_items WHERE idpedido = '$reference'");

if ($consulta_items->num_rows == 0) {
    // No hay ítems para ese pedido
    header("Location: pedido_no_encontrado.php");
    exit();
}

// 3. Obtener información general del pedido
$consulta_pedido = $mysqli->query("SELECT * FROM pagina_compras_mails WHERE reference = '$reference'");

if ($consulta_pedido->num_rows == 0) {
    // El pedido no existe, aunque tenga ítems
    header("Location: pedido_invalido.php");
    exit();
}

$pedido_info = $consulta_pedido->fetch_assoc();

?>
  <?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();
    total= parseInt(total) - parseInt(menos);
    $("#total").html(total);
    
}
</script>
<body class="fixed-nav sidenav-toggled sticky-footer bg-dark" id="page-top">
      <?php include $r."inc/nav.php"; ?>
  <div class="content-wrapper">
    <div class="container-fluid">
      <button id="btnagregar" class="btn btn-primary btn-block <? if($spe!=$pcl){ ?>d-none<?}?>" data-toggle="modal" data-target="#exampleModal"><i class="fa fa-plus"></i> Agregar</button>
      <hr/>
      <form id="formulario" class="pedido" name="pedido" method="post" action="pedir.php">
          <input type="hidden" name="pedir" value="pedir">
        <div class="form-group row">
          <label for="cliente" class="col-sm-2 col-form-label">Cliente</label>
          <div class="col-sm-8">
              <? if($spe!=$pcl){ ?>
              <select data-placeholder="Seleccionar Cliente" class="chosen-select" name="cliente" id="cliente">
                    <? $resultado = $mysqli->query("SELECT * FROM z_clientes WHERE eliminado=0 ORDER BY nombre ASC");
                  do{echo '<option value="'.$fila["id"].'"> '.$fila["nombre"].'</option>';
                    }while ($fila = $resultado->fetch_assoc()); ?>
              </select>
              <? }else{$nombre=$_SESSION['nombre'];$resultado = $mysqli->query("SELECT * FROM z_clientes WHERE nombre='$nombre'");$fila = $resultado->fetch_assoc(); echo "<input type='hidden' value='".$fila["id"]."' name='cliente' id='cliente'>".$fila["nombre"];} ?>
          </div>
          <div class="col-sm-2" id="pedanterior"></div>
        </div>
        <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</b></td>
                <td class="text-danger h6">$ <span id="total">0</span> COP</td>
                <td></td>
           </tr>
          </tfoot>
          <tbody id="tabla">
              <? while($json_string = $consulta_items->fetch_assoc()){
                $data = json_decode($json_string['idproducto'], true);
                $idproducto = $data['idproducto'];
                $infoproducto = sinfo('z_productos' ,$idproducto);
                $presentacion = $data['presentacion'];
                $infopresent = sinfo('z_presentaciones_productos',$presentacion);
                $cantidad = $data['cantidad'];
                $code = $idproducto.$presentacion;
              ?>
                 <tr id="trow<?= $code; ?>">
                     <td><input type="hidden" value="<?= $code; ?>" name="iden<?= $code; ?>"><input type="hidden" value="<?= $idproducto; ?>" name="cod<?= $code; ?>"> <?= $infoproducto['producto']; ?></td>
                     <td><input type="hidden" value="<?= $cantidad; ?>" name="cant<?= $code; ?>"><?= $cantidad.' '.$infopresent['presentacion']; ?><input type="hidden" value="<?= $idproducto; ?>" name="tipo<?= $code; ?>"></td>
                     <td><input type="hidden" value="0" name="prec<?= $code; ?>">$ 0 COP</td><td><input type="hidden" value="0" name="iva<?= $code; ?>">$ 0 COP</td>
                     <td></td>
                </tr> 
              <? } ?>
          </tbody>
        </table>
        <div id="total"></div>
        <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 class="col-sm-2">
              <div class="form-group">
                <input type="radio" name="tipopedido" id="factura" value="F" required>
                <label for="factura">Factura</label>
            </div>
            
            </div>
         <div class="col-sm-2">
              <div class="form-group">
                <input type="radio" name="tipopedido" id="remision" value="R" required checked>
                <label for="remision">Tiquete de Salida</label>
              </div>
          </div>
         <div class="col-sm-2">
              <div class="form-group">
                <input type="radio" name="tipopedido" id="remisionfast" value="RV" required>
                <label for="remision">Inventario</label>
              </div>
          </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-primary btn-sm btn-block" value="Finalizar Pedido">
      </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">
                  <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" 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>
                            <? }; ?>
                      </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>
                            <? $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';} ?> disabled><?= $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" 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>
        
      <?php include $r."inc/foot.php"; ?>
    </div>
  </div>
</body>
</html>