<?php
/**
 * Automated Verification Script for Centralized sincfacturas APIs
 */

$php = 'c:\\wamp64\\bin\\php\\php8.2.29\\php.exe';

function runGET($php, $file, $getParams) {
    $b64 = base64_encode(json_encode($getParams));
    $code = "foreach (json_decode(base64_decode('$b64'), true) as \$k => \$v) { \$_GET[\$k] = \$v; } ";
    $code .= "include '" . addslashes($file) . "';";
    $escaped = str_replace('"', '\"', $code);
    return shell_exec("\"$php\" -r \"$escaped\" 2>&1");
}

function runPOST($php, $file, $jsonData) {
    $b64 = base64_encode(json_encode($jsonData));
    $code = "\$GLOBALS['MOCK_INPUT'] = base64_decode('$b64'); ";
    $code .= "include '" . addslashes($file) . "';";
    $escaped = str_replace('"', '\"', $code);
    return shell_exec("\"$php\" -r \"$escaped\" 2>&1");
}

echo "=== STARTING VERIFICATION OF CENTRALIZED SINCFACTURAS APIS ===\n\n";

// 1. Search products
echo "1. Testing buscar_productos.php (GET query=ace):\n";
$res1 = runGET($php, dirname(__DIR__) . '/api/buscar_productos.php', ['query' => 'ace']);
$json1 = json_decode($res1, true);
if (isset($json1['success']) && $json1['success']) {
    echo "   [SUCCESS] Found " . count($json1['data']) . " products matching 'ace'\n";
    if (count($json1['data']) > 0) {
        echo "   Sample: " . $json1['data'][0]['NombreComercial'] . " (Costo: " . $json1['data'][0]['CostoUnidad'] . ", Precio: " . $json1['data'][0]['PrecioVentaUnidad'] . ")\n";
    }
} else {
    echo "   [FAIL] buscar_productos.php failed or returned invalid response:\n$res1\n";
}

// 2. Obtain mapping
echo "\n2. Testing obtener_mapping.php (GET descripcion=ACETAMINOFEN):\n";
$res2 = runGET($php, dirname(__DIR__) . '/api/obtener_mapping.php', ['descripcion' => 'ACETAMINOFEN']);
$json2 = json_decode($res2, true);
if (isset($json2['success'])) {
    echo "   [SUCCESS] Mapping endpoint executed successfully. Found " . count($json2['mappings'] ?? []) . " mappings/fallbacks\n";
} else {
    echo "   [FAIL] obtener_mapping.php failed:\n$res2\n";
}

// 3. Register Product
echo "\n3. Testing registrar_producto.php (POST):\n";
$testCode = 'TEST_SINC_' . time();
$regPayload = [
    'NombreComercial' => 'Producto Sinc Facturas Test ' . time(),
    'CodigoBarra' => 'BAR_' . time(),
    'NombreGenerico' => 'Test Generico',
    'laboratorio' => 'Laboratorio Test',
    'exento_iva' => 0,
    'FactorBlister' => 10,
    'FactorCaja' => 50,
    'existencia' => 100,
    'CostoUnidad' => 1.50,
    'PrecioVentaUnidad' => 2.50,
    'PrecioVentaBlister' => 22.00,
    'PrecioVentaMayor' => 105.00,
    'id_lugarCompra' => 2,
    'conFactura' => 1,
    'FechaVencimiento' => '31/12/2028',
    'descripcion_factura' => 'TEST FACTURA DESC ' . $testCode
];

$res3 = runPOST($php, dirname(__DIR__) . '/api/registrar_producto.php', $regPayload);
$json3 = json_decode($res3, true);
if (isset($json3['success']) && $json3['success']) {
    $newProductId = $json3['data']['id'];
    $newProductCode = $json3['data']['CodigoInterno'];
    echo "   [SUCCESS] Product registered successfully. ID: $newProductId, Code: $newProductCode\n";
    
    // Validate database writes
    require_once 'c:/wamp64/www/eles/SufarmaERP/config/database.php';
    $pdo = getDBConnection();
    
    // Check presentations
    $stmtP = $pdo->prepare("SELECT presentacion_id, factor_conversion, precio_venta FROM producto_presentaciones WHERE producto_id = :pid");
    $stmtP->execute([':pid' => $newProductId]);
    $presList = $stmtP->fetchAll(PDO::FETCH_ASSOC);
    echo "   - Relational check: Presentaciones count = " . count($presList) . "\n";
    foreach ($presList as $p) {
        echo "     * Pres ID {$p['presentacion_id']}: Factor {$p['factor_conversion']}, Precio Q {$p['precio_venta']}\n";
    }
    
    // Check CPP
    $stmtCPP = $pdo->prepare("SELECT costo_promedio_unidad_base, cantidad_total_unidades, valor_total_inventario FROM productos_costo_promedio WHERE producto_id = :pid");
    $stmtCPP->execute([':pid' => $newProductId]);
    $cpp = $stmtCPP->fetch(PDO::FETCH_ASSOC);
    echo "   - Relational check: CPP = Q {$cpp['costo_promedio_unidad_base']} (Stock: {$cpp['cantidad_total_unidades']} u, Total: Q {$cpp['valor_total_inventario']})\n";

    // Check mapping
    $stmtMap = $pdo->prepare("SELECT descripcion_factura FROM fel_producto_mapping WHERE producto_id = :pid");
    $stmtMap->execute([':pid' => $newProductId]);
    $maps = $stmtMap->fetchAll(PDO::FETCH_COLUMN);
    echo "   - Relational check: Mapping description = " . implode(', ', $maps) . "\n";

    // 4. Upsert Product Maestro
    echo "\n4. Testing upsert_producto_maestro.php (POST):\n";
    $upsertPayload = [
        'producto_id' => $newProductId,
        'descripcion_factura' => 'TEST FACTURA DESC ' . $testCode . ' UPDATED',
        'FactorBlister' => 12,
        'FactorCaja' => 60,
        'PrecioVentaUnidad' => 2.80,
        'PrecioVentaBlister' => 30.00,
        'PrecioVentaMayor' => 130.00,
        'esExento' => 1,
        'costo_unidad' => 1.70,
        'lugar_compra_id' => 3,
        'fecha_factura' => '2026-06-01',
        'conFactura' => 1
    ];
    
    $res4 = runPOST($php, dirname(__DIR__) . '/api/upsert_producto_maestro.php', $upsertPayload);
    $json4 = json_decode($res4, true);
    if (isset($json4['success']) && $json4['success']) {
        echo "   [SUCCESS] Product upserted successfully\n";
        
        // Recheck DB
        $stmtP->execute([':pid' => $newProductId]);
        $presList2 = $stmtP->fetchAll(PDO::FETCH_ASSOC);
        echo "   - Post-upsert check: Presentaciones:\n";
        foreach ($presList2 as $p) {
            echo "     * Pres ID {$p['presentacion_id']}: Factor {$p['factor_conversion']}, Precio Q {$p['precio_venta']}\n";
        }
        
        $stmtCPP->execute([':pid' => $newProductId]);
        $cpp2 = $stmtCPP->fetch(PDO::FETCH_ASSOC);
        echo "   - Post-upsert check: CPP = Q {$cpp2['costo_promedio_unidad_base']} (Stock: {$cpp2['cantidad_total_unidades']} u, Total: Q {$cpp2['valor_total_inventario']})\n";
        
        $stmtMap->execute([':pid' => $newProductId]);
        $maps2 = $stmtMap->fetchAll(PDO::FETCH_COLUMN);
        echo "   - Post-upsert check: Mappings = " . implode(', ', $maps2) . "\n";
        
        // Clean up test database rows
        $pdo->beginTransaction();
        $pdo->prepare("DELETE FROM compras_detalle WHERE producto_id = :pid")->execute([':pid' => $newProductId]);
        $pdo->prepare("DELETE FROM compras WHERE id NOT IN (SELECT compra_id FROM compras_detalle)")->execute();
        $pdo->prepare("DELETE FROM inventario_sucursal WHERE producto_id = :pid")->execute([':pid' => $newProductId]);
        $pdo->prepare("DELETE FROM productos_costo_promedio WHERE producto_id = :pid")->execute([':pid' => $newProductId]);
        $pdo->prepare("DELETE FROM producto_presentaciones WHERE producto_id = :pid")->execute([':pid' => $newProductId]);
        $pdo->prepare("DELETE FROM producto_lugares_compra WHERE producto_id = :pid")->execute([':pid' => $newProductId]);
        $pdo->prepare("DELETE FROM fel_producto_mapping WHERE producto_id = :pid")->execute([':pid' => $newProductId]);
        $pdo->prepare("DELETE FROM productos WHERE id = :pid")->execute([':pid' => $newProductId]);
        $pdo->commit();
        echo "   - Cleaned up test records from database successfully.\n";
    } else {
        echo "   [FAIL] upsert_producto_maestro.php failed:\n$res4\n";
    }

} else {
    echo "   [FAIL] registrar_producto.php failed:\n$res3\n";
}

echo "\n=== VERIFICATION COMPLETED ===\n";
