<?php
// validate.php (支持账号绑定版)

header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0); 
error_reporting(E_ALL);

function sendJson($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// 1. 数据库连接
$host   = '127.0.0.1';
$port   = 3306;
$dbname = 'ea_license';
$user   = 'ea_checker';      
$pass   = 'Fuhua69118600'; // ⚠️记得填密码

$mysqli = new mysqli($host, $user, $pass, $dbname, $port);
if ($mysqli->connect_error) {
    sendJson(['status' => 'error', 'message' => 'DB连接失败']);
}
$mysqli->set_charset("utf8mb4");

// 2. 获取 Key 和 Account (MT4账号)
$input_key = '';
$input_acc = '';

// 尝试获取 JSON 输入
$raw_input = file_get_contents('php://input');
$json_data = json_decode($raw_input, true);

if (isset($json_data['key'])) $input_key = trim($json_data['key']);
if (isset($json_data['account'])) $input_acc = trim($json_data['account']);

// 兼容 POST 表单
if (empty($input_key) && isset($_POST['key'])) $input_key = trim($_POST['key']);
if (empty($input_acc) && isset($_POST['account'])) $input_acc = trim($_POST['account']);

if (empty($input_key)) sendJson(['status' => 'error', 'message' => '未提供密钥']);
// 如果只是验证有效性不绑定，可以允许空账号，但通常 EA 都会发账号过来
if (empty($input_acc)) $input_acc = '0'; 

// 3. 查询数据库
// 获取 id, expiry_date, status, max_accounts, bound_accounts
$sql = "SELECT id, expiry_date, status, max_accounts, bound_accounts FROM licenses WHERE license_key = ? LIMIT 1";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $input_key);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    
    // --- 检查状态 ---
    if ($row['status'] !== 'active') {
        sendJson(['status' => 'error', 'message' => '密钥已被禁用']);
    }
    
    // --- 检查过期 ---
    $expiry = strtotime($row['expiry_date']);
    if (time() > $expiry) {
        sendJson(['status' => 'error', 'message' => '密钥已过期']);
    }

    // ==========================================
    // --- 核心逻辑：账号绑定检查 ---
    // ==========================================
    $current_bound_str = $row['bound_accounts'];
    $max_accounts = intval($row['max_accounts']);
    
    // 将数据库里的字符串 "1001,1002" 转为数组 [1001, 1002]
    $bound_list = [];
    if (!empty($current_bound_str)) {
        $bound_list = explode(',', $current_bound_str);
    }

    // 检查当前请求的账号是否在列表里
    if (in_array($input_acc, $bound_list)) {
        // ✅ 已经在白名单里，通过
        $days = floor(($expiry - time()) / 86400);
        sendJson(['status' => 'ok', 'days_left' => $days, 'message' => '验证成功']);
    } else {
        // ❌ 没在白名单里，检查是否还有空位
        if (count($bound_list) < $max_accounts) {
            // ✅ 还有空位，执行绑定！
            $bound_list[] = $input_acc; // 加进去
            $new_bound_str = implode(',', $bound_list); // 变回字符串
            
            // 更新数据库
            $update_stmt = $mysqli->prepare("UPDATE licenses SET bound_accounts = ? WHERE id = ?");
            $update_stmt->bind_param('si', $new_bound_str, $row['id']);
            
            if ($update_stmt->execute()) {
                $days = floor(($expiry - time()) / 86400);
                sendJson(['status' => 'ok', 'days_left' => $days, 'message' => '新设备绑定成功']);
            } else {
                sendJson(['status' => 'error', 'message' => '绑定账号失败(DB error)']);
            }
            $update_stmt->close();
        } else {
            // ❌ 没有空位了，拒绝
            sendJson(['status' => 'error', 'message' => '授权设备数量已满']);
        }
    }

} else {
    sendJson(['status' => 'error', 'message' => '无效的密钥']);
}

$stmt->close();
$mysqli->close();
?>
