<?php
// api/register.php - 註冊 (cURL 裝甲版)
ini_set('display_errors', 0); // 強制關閉 PHP 報錯，保護 JSON 格式
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);

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

if (empty($username) || empty($email) || empty($password)) {
    echo json_encode(["status" => "error", "message" => "所有欄位皆為必填"]); exit;
}
if (empty($recaptcha_response)) {
    echo json_encode(["status" => "error", "message" => "請勾選「我不是機器人」"]); exit;
}

// 🛡️ 使用強大的 cURL 呼叫 Google
$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 {
    $check = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $check->execute([$username, $email]);
    if ($check->rowCount() > 0) {
        echo json_encode(["status" => "error", "message" => "帳號或信箱已被註冊"]); exit;
    }

    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $sql = "INSERT INTO users (username, email, password, level, coins, created_at) VALUES (?, ?, ?, 0, 0, NOW())";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$username, $email, $hashed_password]);

    echo json_encode(["status" => "success", "message" => "註冊成功！請等待天啟者審核開通。"]);

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "資料庫錯誤"]);
}
?>