<?php
require_once 'config.php';

header('Content-Type: application/json');

$api_key = $_GET['api_key'] ?? $_POST['api_key'] ?? '';
// 简单API密钥验证（可扩展）
if ($api_key !== getSiteConfig('encrypt_api_key')) {
    echo json_encode(['code' => 403, 'message' => 'API密钥错误']);
    exit;
}

$user_id = intval($_GET['user_id'] ?? $_POST['user_id'] ?? 0);
if (!$user_id) {
    echo json_encode(['code' => 400, 'message' => '缺少user_id']);
    exit;
}

$user = $db->fetchOne("SELECT * FROM users WHERE id = $user_id");
if (!$user) {
    echo json_encode(['code' => 404, 'message' => '用户不存在']);
    exit;
}

if (!hasEncryptPermission($user)) {
    echo json_encode(['code' => 403, 'message' => '用户无加密权限']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];
    if ($file['error'] !== UPLOAD_ERR_OK || pathinfo($file['name'], PATHINFO_EXTENSION) !== 'php') {
        echo json_encode(['code' => 400, 'message' => '文件无效']);
        exit;
    }
    $content = file_get_contents($file['tmp_name']);
    $encrypted = encryptPHPCode($content);
    echo json_encode(['code' => 200, 'data' => ['encrypted_code' => $encrypted]]);
    exit;
}

echo json_encode(['code' => 400, 'message' => '请上传PHP文件']);
?>