<?php
/**
 * Automated Verification Script for Centralized sincfacturapro (ProHigh) APIs
 */

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

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 SINCFACTURAPRO (PROHIGH) APIS ===\n\n";

// 1. Test Saving with custom mapped suppliers AND as a simplified Book
echo "1. Testing api/guardar.php (ProHigh Mappings & Simplified Book Saving):\n";

$testStamp = time();
$nuevoProveedorNombre = "Distribuidora ProHigh Test " . $testStamp;
$libroNombre = "Libro de Prueba ProHigh " . $testStamp;

$savePayload = [
    'totalFacturas' => 2,
    'observaciones' => 'Test de integración ProHigh ' . $testStamp,
    'crear_libro' => true,
    'nombre_libro' => $libroNombre,
    'color_libro' => '#a855f7',
    'productos' => [
        // Producto 1: Mapeado a un proveedor existente (ID = 1, General)
        [
            'emisor' => 'PROVEEDOR ORIGINAL A',
            'lugar_compra_id' => 1, // General
            'nuevo_lugar_nombre' => '',
            'numFactura' => 'FAC-98765',
            'descripcion' => 'PRODUCTO PRO TEST A',
            'cantidadTotal' => 10,
            'cantidadBonif' => 0,
            'totalPagado' => 150.00,
            'precioOriginal' => 15.00,
            'tieneBonificacion' => false,
            'consolidado' => false,
            'esExento' => false,
            'fecha' => '2026-06-02'
        ],
        // Producto 2: Mapeado a "NEW" con un nombre personalizado
        [
            'emisor' => 'PROVEEDOR ORIGINAL B S.A.',
            'lugar_compra_id' => 'NEW',
            'nuevo_lugar_nombre' => $nuevoProveedorNombre,
            'numFactura' => 'FAC-43210',
            'descripcion' => 'PRODUCTO PRO TEST B',
            'cantidadTotal' => 20,
            'cantidadBonif' => 5,
            'totalPagado' => 450.00,
            'precioOriginal' => 30.00,
            'tieneBonificacion' => true,
            'consolidado' => true,
            'esExento' => true,
            'fecha' => '2026-06-02'
        ]
    ]
];

$res = runPOST($php, dirname(__DIR__) . '/api/guardar.php', $savePayload);
$json = json_decode($res, true);

if (isset($json['success']) && $json['success']) {
    $importId = $json['importacion_id'];
    $libroId = $json['libro_id'];
    echo "   [SUCCESS] Import saved successfully. Import ID: $importId, Book ID: $libroId\n";

    // 2. Validate Database Writes
    require_once 'c:/wamp64/www/eles/SufarmaERP/config/database.php';
    $pdo = getDBConnection();

    // Verify import header
    $stmtH = $pdo->prepare("SELECT total_facturas, total_productos, total_invertido, observaciones FROM fel_importaciones WHERE id = :id");
    $stmtH->execute([':id' => $importId]);
    $header = $stmtH->fetch(PDO::FETCH_ASSOC);
    
    echo "   - Header check:\n";
    echo "     * Facturas: {$header['total_facturas']} (Expected: 2)\n";
    echo "     * Productos: {$header['total_productos']} (Expected: 2)\n";
    echo "     * Invertido: Q {$header['total_invertido']} (Expected: 600.00)\n";
    echo "     * Obs: {$header['observaciones']}\n";

    // Verify detail writes
    $stmtD = $pdo->prepare("SELECT lugar_compra_id, proveedor_nombre, descripcion, cantidad_total, total_pagado FROM fel_importacion_detalle WHERE importacion_id = :id");
    $stmtD->execute([':id' => $importId]);
    $details = $stmtD->fetchAll(PDO::FETCH_ASSOC);
    
    echo "   - Details check:\n";
    foreach ($details as $d) {
        echo "     * Prod: {$d['descripcion']} | Lugar ID: {$d['lugar_compra_id']} | Proveedor: {$d['proveedor_nombre']} | Pagado: Q {$d['total_pagado']}\n";
    }

    // Verify the newly created custom supplier in lugarcompra
    $stmtL = $pdo->prepare("SELECT id, nombre FROM lugarcompra WHERE nombre = :nombre");
    $stmtL->execute([':nombre' => $nuevoProveedorNombre]);
    $newLugar = $stmtL->fetch(PDO::FETCH_ASSOC);
    
    if ($newLugar) {
        $newLugarId = $newLugar['id'];
        echo "   [SUCCESS] Verified new supplier creation in lugarcompra. ID: $newLugarId, Name: {$newLugar['nombre']}\n";
    } else {
        echo "   [FAIL] Custom supplier not found in database!\n";
    }

    // Verify that the book is created
    $stmtBook = $pdo->prepare("SELECT nombre, color FROM libros WHERE id = :id");
    $stmtBook->execute([':id' => $libroId]);
    $book = $stmtBook->fetch(PDO::FETCH_ASSOC);
    if ($book) {
        echo "   [SUCCESS] Verified book registration. Name: {$book['nombre']} (Expected: $libroNombre), Color: {$book['color']} (Expected: #a855f7)\n";
    } else {
        echo "   [FAIL] Book not found in database!\n";
    }

    // Verify that exactly ONE sheet is created in libro_hojas
    $stmtB = $pdo->prepare("SELECT id, nombre_hoja FROM libro_hojas WHERE libro_id = :lid");
    $stmtB->execute([':lid' => $libroId]);
    $sheets = $stmtB->fetchAll(PDO::FETCH_ASSOC);
    if (count($sheets) === 1) {
        echo "   [SUCCESS] Verified single sheet creation in libro_hojas. Sheet Name: {$sheets[0]['nombre_hoja']}\n";
    } else {
        echo "   [FAIL] Expected exactly 1 sheet, found: " . count($sheets) . "\n";
    }

    // 3. Database Cleanup
    $pdo->beginTransaction();
    // Delete sheet
    $pdo->prepare("DELETE FROM libro_hojas WHERE libro_id = :lid")->execute([':lid' => $libroId]);
    // Delete book
    $pdo->prepare("DELETE FROM libros WHERE id = :lid")->execute([':lid' => $libroId]);
    // Delete import details
    $pdo->prepare("DELETE FROM fel_importacion_detalle WHERE importacion_id = :id")->execute([':id' => $importId]);
    // Delete import header
    $pdo->prepare("DELETE FROM fel_importaciones WHERE id = :id")->execute([':id' => $importId]);
    // Delete custom supplier if created
    if (isset($newLugarId)) {
        $pdo->prepare("DELETE FROM lugarcompra WHERE id = :id")->execute([':id' => $newLugarId]);
    }
    $pdo->commit();
    echo "\n   - Database cleanup completed successfully. DB is clean.\n";

} else {
    echo "   [FAIL] api/guardar.php failed or returned invalid response:\n$res\n";
}

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