<?php

// Quick database bootstrap: ensure required tables exist, otherwise run schema.sql

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/app/Core/Database.php';

use App\Core\Database;
use PDO;
use PDOException;

$schemaPath = __DIR__ . '/database/schema.sql';

if (!file_exists($schemaPath)) {
    exit("Schema file not found at {$schemaPath}\n");
}

try {
    $db = Database::getInstance()->getConnection();
} catch (Throwable $e) {
    exit("Database connection failed: " . $e->getMessage() . "\n");
}

// Extract expected table names from schema
$schemaSql = file_get_contents($schemaPath);
preg_match_all('/CREATE TABLE `([^`]+)`/i', $schemaSql, $matches);
$expectedTables = array_unique($matches[1] ?? []);

if (empty($expectedTables)) {
    exit("No tables found in schema definition.\n");
}

// Get existing tables
try {
    $stmt = $db->query('SHOW TABLES');
    $existingTables = array_map('strtolower', $stmt->fetchAll(PDO::FETCH_COLUMN));
} catch (PDOException $e) {
    exit("Failed to list existing tables: " . $e->getMessage() . "\n");
}

$missingTables = array_values(array_filter($expectedTables, function ($table) use ($existingTables) {
    return !in_array(strtolower($table), $existingTables, true);
}));

if (empty($missingTables)) {
    exit("All required tables are present. No changes made.\n");
}

// Apply schema to create missing tables
try {
    $db->exec($schemaSql);
} catch (PDOException $e) {
    exit("Failed to execute schema.sql: " . $e->getMessage() . "\n");
}

// Confirm creation
$stmt = $db->query('SHOW TABLES');
$postTables = array_map('strtolower', $stmt->fetchAll(PDO::FETCH_COLUMN));
$stillMissing = array_values(array_filter($expectedTables, function ($table) use ($postTables) {
    return !in_array(strtolower($table), $postTables, true);
}));

if (empty($stillMissing)) {
    echo "Created missing tables: " . implode(', ', $missingTables) . "\n";
    exit(0);
}

exit("Schema applied but the following tables are still missing: " . implode(', ', $stillMissing) . "\n");
