<?php
  if(!file_exists("pedidos.txt")){
    echo "<p>No hay pedidos registrados</p>";
    exit;
  }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Listar Ventas</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #6d4c41; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #6d4c41; color: white; }
        .pendiente { color: orange; font-weight: bold; }
        .vendido { color: green; font-weight: bold; }
    </style>
</head>
<body>
    <h3>TODOS LOS PEDIDOS / VENTAS</h3>
    <?php
      $recurso = fopen("pedidos.txt","r");
      echo "<table>";
      echo "<tr><th>Pedido</th><th>NIT/CI</th><th>Cliente</th><th>Fecha</th><th>Estado</th><th>Detalle</th><th>Total</th></tr>";
      while(!feof($recurso)){
        $linea = fgets($recurso);
        if(trim($linea) != ""){
          $reg = explode("|",$linea);
          if(count($reg) >= 5){
            $clase = (trim($reg[4]) == "VENDIDO") ? "vendido" : "pendiente";
            $detalle = "";
            $total = 0;
            if(file_exists("detalle_pedidos.txt")){
              $fd = fopen("detalle_pedidos.txt","r");
              while(!feof($fd)){
                $dl = fgets($fd);
                if(trim($dl) != ""){
                  $dd = explode("|",$dl);
                  if(count($dd) >= 5 && trim($dd[0]) == trim($reg[0])){
                    $detalle .= trim($dd[1])." x".$dd[3]." (".$dd[4]." Bs), ";
                    $total += floatval($dd[4]);
                  }
                }
              }
              fclose($fd);
            }
            echo "<tr>";
            echo "<td>".htmlspecialchars($reg[0])."</td>";
            echo "<td>".htmlspecialchars($reg[1])."</td>";
            echo "<td>".htmlspecialchars($reg[2])."</td>";
            echo "<td>".htmlspecialchars($reg[3])."</td>";
            echo "<td class='$clase'>".htmlspecialchars($reg[4])."</td>";
            echo "<td>".htmlspecialchars(rtrim($detalle,", "))."</td>";
            echo "<td>$total Bs</td>";
            echo "</tr>";
          }
        }
      }
      echo "</table>";
      fclose($recurso);
    ?>
</body>
</html>
