<?php
// server.php

// 获取请求中的device_id参数
$device_id = isset($_REQUEST['device_id']) ? trim($_REQUEST['device_id']) : '';

// 如果没有提供device_id，返回错误
if (empty($device_id)) {
    http_response_code(400);
    echo json_encode(['error' => 'device_id is required']);
    exit;
}

// 读取user_list.json文件
$userListFile = __DIR__ . '/user/user_list.json';
if (!file_exists($userListFile)) {
    http_response_code(500);
    echo json_encode(['error' => 'user list file not found']);
    exit;
}

$userListJson = file_get_contents($userListFile);
$userList = json_decode($userListJson, true);

// 检查JSON解码是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to parse user list']);
    exit;
}

// 逻辑判断
$foundUser = null;
foreach ($userList as $user) {
    if (isset($user['device_id']) && $user['device_id'] === $device_id) {
        $foundUser = $user;
        break;
    }
}

// 路径
$noServerFile  = __DIR__ . '/notice/no_server.json';
$endServerFile = __DIR__ . '/notice/end_server.json';

header('Content-Type: application/json; charset=utf-8');

// 未找到用户，或server为空
if ($foundUser === null || empty($foundUser['server'])) {
    if (file_exists($noServerFile)) {
        echo file_get_contents($noServerFile);
    }
    exit;
}

// 检查是否过期
$today = date('Y-m-d');
if (!empty($foundUser['expire_at']) && $foundUser['expire_at'] < $today) {
    if (file_exists($endServerFile)) {
        echo file_get_contents($endServerFile);
    }
    exit;
}

// 用户存在且未过期 → 不返回任何内容
exit;
