<?php
/**
 * crear_mangueras_automatico.php
 * Lee sale.txt y crea automáticamente las mangueras faltantes
 * Ejecutar una sola vez: http://localhost/fuelpos/crear_mangueras_automatico.php
 */

require_once __DIR__ . '/init.php';

$pdo = pdo();
$salesFile = 'C:/opscode/sale.txt';

if (!file_exists($salesFile)) {
    die("ERROR: Archivo $salesFile no encontrado");
}

$content = file_get_contents($salesFile);
$lines = explode("\n", $content);
$header = null;
$combinations = [];

foreach ($lines as $i => $line) {
    $line = trim($line);
    if ($line === '') continue;
    
    $fields = explode("\t", $line);
    
    if ($i === 0 || $header === null) {
        $header = $fields;
        continue;
    }
    
    $sale = [];
    foreach ($header as $idx => $colName) {
        $sale[$colName] = isset($fields[$idx]) ? trim($fields[$idx]) : '';
    }
    
    $surtidor = (int)$sale['Surtidor'];
    $manguera = trim($sale['Manguera']);
    $productID = (int)$sale['ID Producto'];
    
    if ($surtidor > 0 && $manguera !== '' && $productID > 0) {
        $key = "{$surtidor}_{$manguera}_{$productID}";
        $combinations[$key] = [
            'pump_id' => $surtidor,
            'hose_name' => $manguera,
            'product_id' => $productID
        ];
    }
}

echo "<h2>🔧 Creando mangueras automáticamente desde sale.txt</h2>";
echo "<p>Combinaciones únicas encontradas: <strong>" . count($combinations) . "</strong></p>";
echo "<hr>";

$created = 0;
$skipped = 0;

foreach ($combinations as $combo) {
    $pump_id = $combo['pump_id'];
    $hose_name = $combo['hose_name'];
    $product_id = $combo['product_id'];
    
    // Verificar si ya existe
    $stmt = $pdo->prepare("SELECT id FROM hoses WHERE pump_id = ? AND name = ? LIMIT 1");
    $stmt->execute([$pump_id, $hose_name]);
    
    if ($stmt->fetch()) {
        echo "⏩ <span style='color:gray'>Surtidor {$pump_id}, Manguera {$hose_name} → Ya existe</span><br>";
        $skipped++;
    } else {
        // Crear manguera
        $stmt = $pdo->prepare("INSERT INTO hoses (pump_id, name, product_id) VALUES (?, ?, ?)");
        $stmt->execute([$pump_id, $hose_name, $product_id]);
        
        echo "✅ <span style='color:green'><strong>Creada:</strong> Surtidor {$pump_id}, Manguera {$hose_name}, Producto ID {$product_id}</span><br>";
        $created++;
    }
}

echo "<hr>";
echo "<h3>📊 Resumen</h3>";
echo "<ul>";
echo "<li><strong>Mangueras creadas:</strong> {$created}</li>";
echo "<li><strong>Mangueras existentes:</strong> {$skipped}</li>";
echo "<li><strong>Total procesadas:</strong> " . count($combinations) . "</li>";
echo "</ul>";
echo "<p><a href='index.php'>← Volver al Dashboard</a></p>";