<?php

declare(strict_types=1);

use FecaMailshots\Plugin;
use FecaMailshots\WordPress\ProductionWordPressFacade;

require_once __DIR__ . '/autoload.php';

$setupErrors = [];
$getOption = static function (string $key) use (&$setupErrors): string {
    if (!function_exists('get_option')) {
        throw new \RuntimeException('WordPress get_option() is unavailable while bootstrapping mailshots plugin.');
    }
    $raw = get_option(\FecaMailshots\Admin\SetupAdminPage::OPTION_KEY, []);
    if (!is_array($raw)) {
        $setupErrors[] = 'Mailshots setup option is missing or invalid.';
        return '';
    }
    if (!array_key_exists($key, $raw)) {
        $setupErrors[] = 'Missing setup configuration key: ' . $key;
        return '';
    }
    $value = trim((string) $raw[$key]);
    if ($value === '') {
        $setupErrors[] = 'Empty setup configuration value: ' . $key;
    }
    return $value;
};

$dbConfig = [
    'MYSQL_HOST' => $getOption('db_host'),
    'MYSQL_PORT' => $getOption('db_port'),
    'MYSQL_USER' => $getOption('db_user'),
    'MYSQL_PASSWORD' => $getOption('db_password'),
    'MAILSHOTS_REMOTE_MYSQL_DB' => $getOption('mailshots_db_name'),
    'MEMBERS_REMOTE_MYSQL_DB' => $getOption('members_db_name'),
    'FEN_REMOTE_MYSQL_DB' => $getOption('fen_db_name'),
];

$wp = new ProductionWordPressFacade();
if ($setupErrors !== []) {
    $setupPage = new \FecaMailshots\Admin\SetupAdminPage($wp, array_values(array_unique($setupErrors)), true);
    $setupPage->register();
    return;
}

$container = Plugin::buildContainer($dbConfig, $wp);
$container->get(FecaMailshots\Admin\DataSourcesAdminPage::class)->register();
$container->get(FecaMailshots\Admin\AttachmentsAdminPage::class)->register();
$container->get(FecaMailshots\Admin\PdfAssetsAdminPage::class)->register();
$container->get(FecaMailshots\Admin\MailshotsAdminPage::class)->register();
$container->get(FecaMailshots\Admin\ReviewRecipientsAdminPage::class)->register();
$container->get(FecaMailshots\Admin\MailshotTestAdminPage::class)->register();
$container->get(FecaMailshots\Admin\RunMailshotAdminPage::class)->register();
$container->get(FecaMailshots\Admin\DownloadPdfAdminPage::class)->register();
$container->get(FecaMailshots\Admin\SetupAdminPage::class)->register();
$container->get(FecaMailshots\Admin\ProfileAdminPage::class)->register();
