<?php
/**
 * Script de comparación de bases de datos: local vs producción
 * Genera la estructura completa de tablas, columnas, índices y constraints
 */

require '/var/www/html/config/config.php';

// Conexión producción (usa la config normal del sistema)
$pdoProd = new PDO(
    'mysql:host='.DB_HOST.';port='.DB_PORT.';dbname='.DB_NAME.';charset=utf8mb4',
    DB_USER, DB_PASS,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
);

// Conexión local (MariaDB del docker-compose dev)
$localHost = 'whatsapp-dev-mysql';
$localUser = 'root';
$localPass = 'root_password_2026';
$localDb   = DB_NAME;

$pdoLocal = null;
try {
    $pdoLocal = new PDO(
        "mysql:host={$localHost};port=3306;dbname={$localDb};charset=utf8mb4",
        $localUser, $localPass,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
    );
} catch (Exception $e) {
    // Si el host no es accesible desde el contenedor app, intentar con la dirección de red interna
    $localHost = '172.17.0.1'; // docker bridge gateway
    try {
        $pdoLocal = new PDO(
            "mysql:host={$localHost};port=3306;dbname={$localDb};charset=utf8mb4",
            $localUser, $localPass,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
    } catch (Exception $e2) {
        echo json_encode(['local_error' => $e2->getMessage()]);
        // Continuar solo con producción
    }
}

function getSchema(PDO $pdo, string $dbName): array {
    // Tablas
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    $schema = [];

    foreach ($tables as $table) {
        // Columnas
        $cols = $pdo->query("SHOW FULL COLUMNS FROM `$table`")->fetchAll();
        // Índices
        $indexes = $pdo->query("SHOW INDEX FROM `$table`")->fetchAll();
        // CREATE TABLE para referencia exacta
        $create = $pdo->query("SHOW CREATE TABLE `$table`")->fetch();

        $schema[$table] = [
            'columns'      => $cols,
            'indexes'      => $indexes,
            'create_sql'   => $create['Create Table'] ?? '',
        ];
    }
    return $schema;
}

function getRowCounts(PDO $pdo): array {
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    $counts = [];
    foreach ($tables as $t) {
        $r = $pdo->query("SELECT COUNT(*) as n FROM `$t`")->fetch();
        $counts[$t] = (int)($r['n'] ?? 0);
    }
    return $counts;
}

$prodSchema   = getSchema($pdoProd, DB_NAME);
$prodCounts   = getRowCounts($pdoProd);
$localSchema  = $pdoLocal ? getSchema($pdoLocal, $localDb) : null;
$localCounts  = $pdoLocal ? getRowCounts($pdoLocal) : null;

$output = [
    'prod_tables'   => array_keys($prodSchema),
    'local_tables'  => $localSchema ? array_keys($localSchema) : null,
    'prod_counts'   => $prodCounts,
    'local_counts'  => $localCounts,
    'prod_schema'   => $prodSchema,
    'local_schema'  => $localSchema,
];

file_put_contents('/tmp/db_scan_result.json', json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
echo "DONE: " . count($prodSchema) . " prod tables" . ($localSchema ? ", " . count($localSchema) . " local tables" : ", local not available") . PHP_EOL;
echo "Output saved to /tmp/db_scan_result.json" . PHP_EOL;
