<?php
/**
 * Admin Bootstrap
 * Ensures autoloader, environment and database are initialized
 */

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

// Load Environment Variables if not already loaded
if (!isset($_ENV['DB_PATH'])) {
    $dotenv = Dotenv\Dotenv::createUnsafeImmutable(__DIR__ . '/../../');
    $dotenv->safeLoad();
}

\Core\Auth::startSession();

// Global PDO setup
if (!isset($GLOBALS['pdo'])) {
    $tenantId = \Core\MultiTenancy::getTenantId();
    $dbPath = \Core\MultiTenancy::getDatabasePath($tenantId);
    if (!file_exists($dbPath)) {
        $dbTemplate = getenv('DB_PATH') ?: 'database.sqlite';
        copy(__DIR__ . '/../../' . $dbTemplate, $dbPath);
    }
    try {
        $pdo = new PDO('sqlite:' . $dbPath);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $GLOBALS['pdo'] = $pdo;

        // Initialize Models
        \Core\Model::setPdo($pdo);
        \Models\PostType::setPdo($pdo);
        \Models\CustomPost::setPdo($pdo);
        \Models\Taxonomy::setPdo($pdo);
        \Models\Media::setPdo($pdo);
    } catch (PDOException $e) {
        die('Admin Bootstrap Error: ' . $e->getMessage());
    }
}

$currentScript = basename($_SERVER['SCRIPT_NAME'] ?? '');
$forceAllowed = ['login.php', 'force-password.php'];
if (\Core\Auth::check() && \Core\Auth::needsPasswordReset() && !in_array($currentScript, $forceAllowed, true)) {
    header('Location: /admin/force-password.php');
    exit;
}
