<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_email_reverse.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_mail.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_mail_settings.php';

fate_admin_require_login_api();

$csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
if (!fate_admin_csrf_check($csrf)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'CSRF 驗證失敗'], JSON_UNESCAPED_UNICODE);
    exit;
}

$action = isset($_POST['action']) && is_string($_POST['action']) ? trim($_POST['action']) : '';

if ($action === 'test_imap') {
    $res = fate_reverse_imap_test();
    if (!$res['ok']) {
        echo json_encode([
            'ok' => false,
            'error' => $res['error'] ?? 'IMAP 連線失敗',
            'mailbox' => $res['mailbox'] ?? '',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    echo json_encode([
        'ok' => true,
        'mailbox' => $res['mailbox'] ?? '',
        'address' => $res['address'] ?? '',
        'total' => $res['total'] ?? 0,
        'unseen' => $res['unseen'] ?? 0,
        'notice' => '連線成功：信箱可正常讀取，反向驗證可運作。',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'preview_verify') {
    $draft = fate_mail_settings_normalize(fate_mail_settings_read());
    if (isset($_POST['verify_subject']) && is_string($_POST['verify_subject'])) {
        $draft['verify_subject'] = $_POST['verify_subject'];
    }
    if (isset($_POST['verify_body_plain']) && is_string($_POST['verify_body_plain'])) {
        $draft['verify_body_plain'] = $_POST['verify_body_plain'];
    }
    if (isset($_POST['verify_body_html']) && is_string($_POST['verify_body_html'])) {
        $draft['verify_body_html'] = $_POST['verify_body_html'];
    }
    $rendered = fate_mail_render_verify_email($draft);
    echo json_encode([
        'ok' => true,
        'subject' => $rendered['subject'],
        'plaintext' => $rendered['plaintext'],
        'html' => $rendered['html'],
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'test_send_verify') {
    $to = isset($_POST['test_email']) ? trim((string) $_POST['test_email']) : '';
    if ($to === '' || filter_var($to, FILTER_VALIDATE_EMAIL) === false) {
        echo json_encode(['ok' => false, 'error' => '請填寫有效的測試收件信箱'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $rendered = fate_mail_render_verify_email(null);
    $payload = [
        'to' => $to,
        'subject' => $rendered['subject'],
        'plaintext' => $rendered['plaintext'],
    ];
    if ($rendered['html'] !== '') {
        $payload['html'] = $rendered['html'];
    }

    $sent = fate_mail_send_transactional($payload);
    if (!$sent['ok']) {
        echo json_encode([
            'ok' => false,
            'error' => $sent['detail'] ?? '發信失敗',
            'transport' => $sent['transport'] ?? '',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    echo json_encode([
        'ok' => true,
        'notice' => '驗證信測試已送出（連結與驗證碼為示意值，無法真正完成驗證）',
        'detail' => $sent['detail'] ?? '',
        'transport' => $sent['transport'] ?? '',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'test_send') {
    $to = isset($_POST['test_email']) ? trim((string) $_POST['test_email']) : '';
    if ($to === '' || filter_var($to, FILTER_VALIDATE_EMAIL) === false) {
        echo json_encode(['ok' => false, 'error' => '請填寫有效的測試收件信箱'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $sent = fate_mail_send_transactional([
        'to' => $to,
        'subject' => 'XSPA 系統發信測試',
        'plaintext' => '這是一封測試信，代表 ' . date('Y-m-d H:i:s') . ' 的發信管道可用。',
    ]);

    if (!$sent['ok']) {
        echo json_encode([
            'ok' => false,
            'error' => $sent['detail'] ?? '發信失敗',
            'transport' => $sent['transport'] ?? '',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    echo json_encode([
        'ok' => true,
        'notice' => '已送出（mail() 回 true 僅表示主機收下，不保證送達；若未收到請查垃圾信或改設 Brevo）',
        'detail' => $sent['detail'] ?? '',
        'transport' => $sent['transport'] ?? '',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'error' => '未知 action'], JSON_UNESCAPED_UNICODE);
