<?php
session_start();
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => '权限不足']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => '方法不允许']);
    exit;
}

$type = $_POST['type'] ?? '';
$filename = $_POST['filename'] ?? '';

if (!in_array($type, ['background', 'avatar']) || empty($filename)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => '参数错误']);
    exit;
}

$src_dir = __DIR__ . '/../src/';
$history_file = $src_dir . $filename;

// 验证历史文件是否存在
if (!file_exists($history_file)) {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => '历史文件不存在']);
    exit;
}

// 获取文件扩展名
$extension = pathinfo($filename, PATHINFO_EXTENSION);

// 确定目标文件名
if ($type === 'background') {
    $target_file = $src_dir . 'backpic.' . $extension;
    $old_files = glob($src_dir . 'backpic.*');
} else {
    $target_file = $src_dir . 'avatar.' . $extension;
    $old_files = glob($src_dir . 'avatar.*');
}

// 删除旧的当前文件
foreach ($old_files as $old_file) {
    if (basename($old_file) !== $filename && file_exists($old_file)) {
        unlink($old_file);
    }
}

// 复制历史文件为当前文件
if (copy($history_file, $target_file)) {
    echo json_encode([
        'success' => true, 
        'message' => ($type === 'background' ? '背景图' : '头像') . '已应用'
    ]);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => '应用失败']);
}
?>