<?php
/**
 * CMS 域名授权查询接口
 */
require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$domain = '';

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $domain = trim($input['domain'] ?? $_POST['domain'] ?? '');
} else {
    $domain = trim($_GET['domain'] ?? '');
}

if (empty($domain)) {
    echo json_encode(['success' => false, 'message' => '缺少域名参数']);
    exit;
}

$domain = preg_replace('#^https?://#', '', $domain);
$domain = rtrim($domain, '/');
$domain = strtolower($domain);

$license = db_query_one("SELECT * FROM licenses WHERE domain = ?", [$domain]);

if (!$license) {
    echo json_encode(['success' => false, 'message' => '该域名未授权', 'code' => 'NOT_FOUND']);
    exit;
}

$now = time();
$expires_at = strtotime($license['expires_at']);
$days_left = max(0, ceil(($expires_at - $now) / 86400));

if ($license['status'] == 0) {
    echo json_encode(['success' => false, 'message' => '该域名已被封禁', 'code' => 'BANNED']);
    exit;
}

if ($expires_at < $now) {
    echo json_encode(['success' => false, 'message' => '授权已过期', 'code' => 'EXPIRED', 'data' => ['expires_at' => $license['expires_at']]]);
    exit;
}

echo json_encode([
    'success' => true,
    'message' => '授权有效',
    'code' => 'VALID',
    'data' => [
        'domain' => $license['domain'],
        'expires_at' => $license['expires_at'],
        'days_left' => $days_left,
        'status' => $license['status']
    ]
]);
