<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_admin_members.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_tier.php';

fate_admin_require_login_api();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method_not_allowed'], JSON_UNESCAPED_UNICODE);
    exit;
}

$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' => '工作階段逾期或驗證失敗，請重新整理後再試。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$actingAdminId = (int) ($_SESSION['fate_admin_member_id'] ?? 0);
$memberId = isset($_POST['member_id']) ? (int) $_POST['member_id'] : 0;
$action = isset($_POST['action']) && is_string($_POST['action']) ? trim($_POST['action']) : '';
$editUrl = isset($_POST['edit_url']) && is_string($_POST['edit_url']) ? trim($_POST['edit_url']) : '';

$respond = static function (bool $ok, array $extra = []): void {
    $payload = array_merge(['ok' => $ok], $extra);
    if (!$ok && !isset($payload['error'])) {
        $payload['error'] = '操作失敗';
    }
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
};

try {
    require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
} catch (Throwable $e) {
    http_response_code(500);
    $respond(false, ['error' => '無法連線資料庫']);
}

$pdo = $GLOBALS['pdo'] ?? null;
if (!$pdo instanceof PDO) {
    http_response_code(500);
    $respond(false, ['error' => '無法連線資料庫']);
}

if (!fate_admin_members_table_exists($pdo)) {
    http_response_code(404);
    $respond(false, ['error' => '會員表不存在']);
}

$allowed = ['approve', 'verify_email', 'clear_email_verify', 'toggle_active', 'save', 'quick_save', 'create'];
if (!in_array($action, $allowed, true)) {
    http_response_code(400);
    $respond(false, ['error' => '未知的操作']);
}

if ($action === 'create') {
    $createRes = fate_admin_members_create($pdo, fate_admin_members_create_input_from_request($_POST), $actingAdminId);
    if (empty($createRes['ok'])) {
        http_response_code(400);
        $respond(false, ['error' => (string) ($createRes['err'] ?? '新增失敗')]);
    }
    $newId = (int) ($createRes['id'] ?? 0);
    if ($newId <= 0) {
        http_response_code(500);
        $respond(false, ['error' => '新增失敗：未取得會員 ID']);
    }
    $redirect = 'members.php?page=1&edit=' . $newId . '&created=1';
    $respond(true, [
        'message' => '已新增會員 #' . $newId,
        'member_id' => $newId,
        'redirect' => $redirect,
    ]);
}

if ($memberId <= 0) {
    http_response_code(400);
    $respond(false, ['error' => '無效的會員 ID']);
}

$res = ['ok' => false, 'err' => '操作失敗'];
$message = '已儲存變更';

if ($action === 'approve') {
    $res = fate_admin_members_approve($pdo, $memberId, $actingAdminId);
    $message = '已通過審核';
} elseif ($action === 'verify_email') {
    $res = fate_admin_members_update($pdo, $memberId, ['email_verified' => true], $actingAdminId);
    $message = '已標記信箱已驗證';
} elseif ($action === 'clear_email_verify') {
    $res = fate_admin_members_update($pdo, $memberId, ['email_verified' => false], $actingAdminId);
    $message = '已清除信箱驗證狀態';
} elseif ($action === 'toggle_active') {
    $res = fate_admin_members_toggle_active($pdo, $memberId, $actingAdminId);
    $message = '已更新啟用狀態';
} elseif ($action === 'save') {
    $roleIn = isset($_POST['role']) && is_string($_POST['role']) ? $_POST['role'] : 'member';
    $statusIn = isset($_POST['status']) && is_string($_POST['status']) ? $_POST['status'] : '1';
    $displayName = isset($_POST['display_name']) && is_string($_POST['display_name']) ? $_POST['display_name'] : '';
    $res = fate_admin_members_update($pdo, $memberId, [
        'display_name' => $displayName,
        'role' => $roleIn,
        'member_tier' => isset($_POST['member_tier']) && is_string($_POST['member_tier']) ? $_POST['member_tier'] : 'register',
        'active' => $statusIn === '1',
    ], $actingAdminId);
    $message = '已儲存變更';
} elseif ($action === 'quick_save') {
    $patch = [];
    if (array_key_exists('display_name', $_POST) && is_string($_POST['display_name'])) {
        $patch['display_name'] = $_POST['display_name'];
    }
    if (array_key_exists('role', $_POST) && is_string($_POST['role'])) {
        $patch['role'] = $_POST['role'];
    }
    if (array_key_exists('member_tier', $_POST) && is_string($_POST['member_tier'])) {
        $patch['member_tier'] = $_POST['member_tier'];
    }
    if (array_key_exists('status', $_POST) && is_string($_POST['status'])) {
        $patch['active'] = $_POST['status'] === '1';
    }
    if ($patch === []) {
        http_response_code(400);
        $respond(false, ['error' => '未指定要更新的欄位']);
    }
    $res = fate_admin_members_update($pdo, $memberId, $patch, $actingAdminId);
    $message = '已更新';
}

if (empty($res['ok'])) {
    http_response_code(400);
    $respond(false, ['error' => (string) ($res['err'] ?? '操作失敗')]);
}

$row = fate_admin_members_fetch_by_id($pdo, $memberId);
if (!is_array($row)) {
    http_response_code(404);
    $respond(false, ['error' => '找不到會員']);
}

$overview = fate_admin_members_overview($pdo);
$hasManualReview = !empty($overview['features']['manual_review']);
$hasEmail = !empty($overview['features']['email']);
$hasEmailVerified = !empty($overview['features']['email_verified']);
$hasMemberTier = !empty($overview['features']['member_tier']);
$hasLastLogin = !empty($overview['features']['last_login']);

$memberPayload = fate_admin_members_row_api_payload($row, [
    'has_manual_review' => $hasManualReview,
    'has_email' => $hasEmail,
    'has_email_verified' => $hasEmailVerified,
    'has_member_tier' => $hasMemberTier,
    'has_last_login' => $hasLastLogin,
    'acting_admin_id' => $actingAdminId,
    'edit_url' => $editUrl,
]);

$respond(true, [
    'message' => $message,
    'member' => $memberPayload,
    'overview' => fate_admin_members_overview_api_payload($overview),
]);
