<?php
/**
 * Docker DB initializer — run via PHP CLI during container startup.
 * Uses the app's own prefix_query() / runSQL() so table prefix is applied correctly.
 */

$db_host     = getenv('DB_HOST')     ?: 'db';
$db_user     = getenv('DB_USER')     ?: 'videodb';
$db_password = getenv('DB_PASSWORD') ?: 'videodb_secret';
$db_name     = getenv('DB_NAME')     ?: 'videodb';
$db_prefix   = getenv('DB_PREFIX')   ?: 'videodb_';

// Load install helpers (prefix_query, runSQL)
require_once '/var/www/html/core/install.core.php';

// Connect
$dbh = @mysqli_connect($db_host, $db_user, $db_password, $db_name);
if (!$dbh) {
    fwrite(STDERR, "[init-db] ERROR: Cannot connect to MySQL: " . mysqli_connect_error() . "\n");
    exit(1);
}

// Idempotency check — skip if already initialized
$result = mysqli_query($dbh, "SHOW TABLES LIKE '{$db_prefix}videodata'");
if ($result && mysqli_num_rows($result) > 0) {
    echo "[init-db] Database already initialized — skipping.\n";
    mysqli_close($dbh);
    exit(0);
}

echo "[init-db] Initializing database schema (prefix: {$db_prefix})...\n";

$sql = file_get_contents('/var/www/html/install/install.sql');
if (!$sql) {
    fwrite(STDERR, "[init-db] ERROR: Cannot read install/install.sql\n");
    exit(1);
}

// Strip comment lines (# …) — the SQL parser in runSQL() does not strip them
$sql = preg_replace('/^\s*#[^\n]*\n/m', "\n", $sql);

if (runSQL($sql, $dbh) === false) {
    fwrite(STDERR, "[init-db] ERROR: Schema install failed: " . mysqli_error($dbh) . "\n");
    exit(1);
}

echo "[init-db] Database initialized successfully.\n";
mysqli_close($dbh);
