<?php
  $nit = $_POST["nit"] ?? "";
  $cliente = $_POST["cliente"] ?? "";

  if($nit == "" || $cliente == ""){
    echo "<p style='color:red'>Error: NIT/CI y nombre son obligatorios</p>";
    echo "<a href='formRegistrarPedido.php'>Volver</a>";
    exit;
  }

  // Generar numero de pedido autoincremental
  $numPedido = "PED00001";
  if(file_exists("pedidos.txt")){
    $recurso = fopen("pedidos.txt","r");
    while(!feof($recurso)){
      $linea = fgets($recurso);
      if(trim($linea) != ""){
        $reg = explode("|",$linea);
        if(count($reg) >= 1){
          $ultimo = trim($reg[0]);
          if(preg_match('/PED(\d+)/',$ultimo,$m)){
            $num = intval($m[1]) + 1;
            $numPedido = "PED" . str_pad($num, 5, "0", STR_PAD_LEFT);
          }
        }
      }
    }
    fclose($recurso);
  }

  $fecha = date("Y-m-d H:i:s");
  $registroPedido = $numPedido."|".$nit."|".$cliente."|".$fecha."|PENDIENTE";

  $recurso = fopen("pedidos.txt","a");
  fwrite($recurso, $registroPedido."\n");
  fclose($recurso);

  // Registrar detalle del pedido
  $total = 0;
  for($i=0; $i<5; $i++){
    $codProducto = $_POST["producto_$i"] ?? "";
    $cantidad = intval($_POST["cantidad_$i"] ?? 0);

    if($codProducto != "" && $cantidad > 0){
      // Buscar precio del producto
      if(file_exists("productos.txt")){
        $fp = fopen("productos.txt","r");
        while(!feof($fp)){
          $linea = fgets($fp);
          if(trim($linea) != ""){
            $p = explode("|",$linea);
            if(count($p) >= 5 && trim($p[0]) == $codProducto){
              $precio = floatval($p[3]);
              $subtotal = $precio * $cantidad;
              $total += $subtotal;

              $registroDetalle = $numPedido."|".trim($p[1])."|".$precio."|".$cantidad."|".$subtotal;
              $fd = fopen("detalle_pedidos.txt","a");
              fwrite($fd, $registroDetalle."\n");
              fclose($fd);
              break;
            }
          }
        }
        fclose($fp);
      }
    }
  }

  echo "<h3 style='color:green'>Pedido registrado exitosamente!</h3>";
  echo "<p><strong>Pedido:</strong> $numPedido</p>";
  echo "<p><strong>Cliente:</strong> $cliente ($nit)</p>";
  echo "<p><strong>Fecha:</strong> $fecha</p>";
  echo "<p><strong>Total:</strong> $total Bs</p>";
  echo "<p><a href='formRegistrarPedido.php'>Otro pedido</a> | <a href='formRegistrarVenta.php' target='_parent'>Consolidar venta</a></p>";
?>
