<?php
// Simple importer for persons2.sql to bypass phpMyAdmin timeouts.
// Place this file on the host and run via CLI:
//   php scripts/import_persons2.php
// or via browser once (protect it afterwards).

set_time_limit(0);
ini_set('memory_limit', '512M');

require __DIR__ . '/../vendor/autoload.php';

$dbConfig = require __DIR__ . '/../app/config/database.php';

$dsn = sprintf(
    'mysql:host=%s;dbname=%s;charset=%s',
    $dbConfig['host'],
    $dbConfig['database'],
    $dbConfig['charset'] ?? 'utf8mb4'
);

try {
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password'], $dbConfig['options'] ?? []);
    $pdo->exec('SET FOREIGN_KEY_CHECKS=0');
} catch (Exception $e) {
    exit("DB connection failed: " . $e->getMessage() . PHP_EOL);
}

$sqlFile = __DIR__ . '/../persons2.sql';
if (!file_exists($sqlFile)) {
    exit("SQL file not found: $sqlFile" . PHP_EOL);
}

$file = new SplFileObject($sqlFile, 'r');
$statement = '';
$count = 0;
$errors = 0;

function flushStatement(PDO $pdo, string &$statement, int &$count, int &$errors)
{
    $trimmed = trim($statement);
    if ($trimmed === '') {
        $statement = '';
        return;
    }
    // If statement is persons insert, convert to INSERT IGNORE to skip duplicates
    if (stripos($trimmed, 'INSERT INTO `persons`') === 0) {
        $trimmed = str_ireplace('INSERT INTO `persons`', 'INSERT IGNORE INTO `persons`', $trimmed);
    }

    try {
        $pdo->exec($trimmed);
        $count++;
        if ($count % 50 === 0) {
            echo "Executed {$count} statements..." . PHP_EOL;
            if (function_exists('ob_flush')) {
                @ob_flush();
                @flush();
            }
        }
    } catch (Exception $e) {
        $errors++;
        echo "Error on statement {$count}: " . $e->getMessage() . PHP_EOL;
    }
    $statement = '';
}

while (!$file->eof()) {
    $line = $file->fgets();
    $trim = ltrim($line);

    // Skip comments
    if (strpos($trim, '--') === 0 || strpos($trim, '/*') === 0) {
        continue;
    }

    $statement .= $line;
    // crude split on semicolon at line end (sufficient for this dump)
    if (substr(rtrim($line), -1) === ';') {
        flushStatement($pdo, $statement, $count, $errors);
    }
}

// Flush any remaining
flushStatement($pdo, $statement, $count, $errors);

$pdo->exec('SET FOREIGN_KEY_CHECKS=1');

echo "Done. Statements executed: {$count}, errors: {$errors}" . PHP_EOL;
