<?php
/**
 * Go 面试闯关 · 公开 API 入口
 *
 * 管理后台：admin.php?k={admin_slug}（密钥在配置中，勿公开）
 * 小程序 / Web：?token=MP令牌&action=... ，用户接口另需 X-User-Session
 * 支付回调：POST ?action=pay_notify
 */

declare(strict_types=1);
session_start();

require __DIR__ . '/bootstrap.php';
require __DIR__ . '/routes/api.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, X-MP-Token, X-User-Session, X-Requested-With, Accept');
    exit;
}

$cfg = load_config();
set_app_cfg($cfg);
$action = (string)($_GET['action'] ?? '');

if ($action === 'pay_notify') {
    handle_pay_notify($cfg);
}

if ($action !== '') {
    handle_api_routes($cfg, $action);
}

// 根路径不暴露后台入口
http_response_code(404);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Not Found'], JSON_UNESCAPED_UNICODE);
exit;
