<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';

fate_public_session_start();

if (fate_public_member_current() !== null) {
    header('Location: ./', true, 302);
    exit;
}

$safeNext = static function (?string $next): string {
    return fate_public_sanitize_login_next($next);
};

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nextPost = $safeNext(isset($_POST['next']) ? (string) $_POST['next'] : null);
    $un = isset($_POST['username']) && is_string($_POST['username']) ? $_POST['username'] : '';
    $pw = isset($_POST['password']) && is_string($_POST['password']) ? $_POST['password'] : '';

    $redirectWithErr = static function (string $errCode, string $username, string $nextUrl): void {
        $_SESSION['fate_login_flash'] = [
            'err' => $errCode,
            'username' => $username,
        ];
        header('Location: login.php?next=' . rawurlencode($nextUrl), true, 303);
        exit;
    };

    if (!fate_admin_member_auth_ready()) {
        header('Location: login.php?reason=badconfig', true, 303);
        exit;
    }

    $pdo = null;
    try {
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
            $pdo = $GLOBALS['pdo'];
        }
    } catch (Throwable) {
        $redirectWithErr('db', $un, $nextPost);
    }

    if (!$pdo instanceof PDO) {
        $redirectWithErr('db', $un, $nextPost);
    }

    $auth = fate_public_member_authenticate($pdo, $un, $pw);
    if ($auth['ok']) {
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_session_bridge.php';
        $remember = !empty($_POST['remember']);
        fate_session_assign_cookie_lifetime(
            $remember ? fate_session_lifetime_sec() : fate_session_short_lifetime_sec()
        );
        fate_public_member_bind_session($auth['member']);
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_profile.php';
        fate_member_profile_hydrate_session($pdo, (int) $auth['member']['id']);
        header('Location: ' . $nextPost, true, 303);
        exit;
    }

    $ae = $auth['err'] ?? '';
    if ($ae === 'email_unverified') {
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_account.php';
        $cred = fate_public_member_verify_credentials($pdo, $un, $pw);
        if ($cred['ok'] && is_array($cred['member'] ?? null)) {
            require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_session_bridge.php';
            fate_session_assign_cookie_lifetime(fate_session_short_lifetime_sec());
            fate_public_member_bind_session($cred['member'], false);
            require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_profile.php';
            fate_member_profile_hydrate_session($pdo, (int) $cred['member']['id']);
            header('Location: ' . $nextPost, true, 303);
            exit;
        }
    }

    if ($ae === 'pending_approval') {
        $redirectWithErr('pending_approval', $un, $nextPost);
    }
    if ($ae === 'missing_table') {
        $redirectWithErr('missing_table', $un, $nextPost);
    }
    if ($ae === 'bad_column') {
        $redirectWithErr('bad_column', $un, $nextPost);
    }
    if ($ae === 'inactive') {
        $redirectWithErr('inactive', $un, $nextPost);
    }
    $redirectWithErr('bad', $un, $nextPost);
}

require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_template.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ui_settings.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_admin_nav_visibility.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_plugins.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_page_counter.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_seo.php';

$flash = isset($_SESSION['fate_login_flash']) && is_array($_SESSION['fate_login_flash'])
    ? $_SESSION['fate_login_flash'] : null;
unset($_SESSION['fate_login_flash']);

$next = $safeNext(isset($_GET['next']) ? (string) $_GET['next'] : null);
$reason = isset($_GET['reason']) ? (string) $_GET['reason'] : '';
$registered = isset($_GET['registered']) && $_GET['registered'] === '1';

$err = is_array($flash) && isset($flash['err']) && is_string($flash['err']) ? $flash['err'] : '';
$stickyLoginUsername = is_array($flash) && isset($flash['username']) && is_string($flash['username']) ? $flash['username'] : '';
$msgOk = '';
if ($registered && is_array($flash) && !empty($flash['ok'])) {
    $msgOk = (string) ($flash['text'] ?? '帳號已建立，請登入。');
} elseif ($registered) {
    $msgOk = '帳號已建立，請登入。';
}

$fatePublicMember = null;
$fateAdminNavVisible = fate_admin_nav_visible_for_frontend();
$fateForumNavVisible = fate_store_forum_plugin_active();

$pdo = null;
try {
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $pdo = $GLOBALS['pdo'];
    }
} catch (Throwable) {
    $pdo = null;
}

$fateBrand = fate_public_site_branding();
$fatePageTitle = $fateBrand['title_main'] . ' — 登入';
$fateSeoContext = fate_seo_private_page_context();
$fatePageStatsFooter = fate_page_stats_for_footer($pdo, 'member.login', null, $fatePageTitle);
$fatePageHitCount = $fatePageStatsFooter['fatePageHitCount'];
$fatePageStatsDbOk = $fatePageStatsFooter['fatePageStatsDbOk'];

header('Content-Type: text/html; charset=UTF-8');

fate_render_login(compact(
    'next',
    'reason',
    'msgOk',
    'err',
    'stickyLoginUsername',
    'fatePublicMember',
    'fateAdminNavVisible',
    'fateForumNavVisible',
    'fatePageHitCount',
    'fatePageStatsDbOk',
    'fatePageTitle',
    'fateSeoContext',
));
