<?php

declare(strict_types=1);

/**
 * 反向 Email 驗證端點（AJAX）：
 * 會員從註冊信箱寄空信到驗證信箱後，按「Verify & Activate」呼叫本端點，
 * 後端以 IMAP 檢查 INBOX 未讀來信，命中即標記已驗證並回傳 JSON。
 */

header('Content-Type: application/json; charset=UTF-8');

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';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_email_reverse.php';

fate_public_session_start();

$member = fate_public_member_current();
if ($member === null) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'verified' => false, 'error' => '請先登入後再驗證。'], JSON_UNESCAPED_UNICODE);
    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) {
}

if (!$pdo instanceof PDO) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'verified' => false, 'error' => '無法連線資料庫，請稍後再試。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$memberId = (int) $member['id'];
$err = null;
$res = fate_member_email_reverse_verify($pdo, $memberId, $err);

if ($res['verified'] && is_array($res['member'])) {
    // 與 token 驗證流程一致：重綁 session、更新個人資料快取
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_session_bridge.php';
    fate_public_member_bind_session($res['member'], true);
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_profile.php';
    fate_member_profile_hydrate_session($pdo, $memberId);
    $_SESSION['fate_email_just_verified'] = true;

    echo json_encode([
        'ok' => true,
        'verified' => true,
        'message' => 'Email 驗證成功，帳號已啟用。',
        'redirect' => './member_profile.php',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode([
    'ok' => (bool) $res['ok'],
    'verified' => false,
    'error' => $err ?? '驗證未通過，請稍後再試。',
], JSON_UNESCAPED_UNICODE);
