<?php
// api/login.php - 登入 (cURL 裝甲版)
ini_set('display_errors', 0);
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$input = json_decode(file_get_contents("php://input"), true);

$account = isset($input['account']) ? trim($input['account']) : '';
$password = isset($input['password']) ? $input['password'] : '';
$recaptcha_response = isset($input['recaptcha_token']) ? $input['recaptcha_token'] : '';

if (empty($account) || empty($password)) {
    echo json_encode(["status" => "error", "message" => "帳號與密碼不得為空"]); exit;
}
if (empty($recaptcha_response)) {
    echo json_encode(["status" => "error", "message" => "請勾選「我不是機器人」"]); exit;
}

// 🛡️ cURL 驗證
$secret_key = '6LeRU24sAAAAAM6WDz5OvWQx1QkdaWoWr0fsxUVQ'; 
$verify_url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => $secret_key, 'response' => $recaptcha_response];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $verify_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$verify_result = curl_exec($ch);
curl_close($ch);

$captcha_success = json_decode($verify_result);

if (!$captcha_success || $captcha_success->success == false) {
    echo json_encode(["status" => "error", "message" => "機器人防禦系統攔截"]); exit;
}

try {
    $sql = "SELECT id, username, email, password, level, coins FROM users WHERE username = ? OR email = ? LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$account, $account]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode(["status" => "error", "message" => "找不到此帳號"]); exit;
    }

    $password_match = password_verify($password, $user['password']) || ($password === $user['password']);

    if ($password_match) {
        if ($user['level'] < 0) {
            echo json_encode(["status" => "error", "message" => "⛔ 此帳號已被天啟者凍結，禁止存取。"]); exit;
        }
        if ($user['level'] == 0) {
            echo json_encode(["status" => "error", "message" => "⏳ 帳號審核中，請靜候天啟者開通。"]); exit;
        }

        echo json_encode([
            "status" => "success",
            "message" => "登入成功",
            "user" => ["user_id" => $user['id'], "username" => $user['username'], "level" => $user['level'], "coins" => $user['coins']]
        ]);
    } else {
        echo json_encode(["status" => "error", "message" => "密碼錯誤"]);
    }
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "資料庫錯誤"]);
}
?>