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

require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();
require_once dirname(__DIR__) . '/core/lib/common.php';

$action = isset($_GET['action']) ? $_GET['action'] : 'upload';

if ($action === 'upload') {
    if (empty($_SESSION['member_id'])) {
        echo json_encode(['code' => 401, 'msg' => '请先登录会员中心'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    requireMemberCsrfToken(true);
    $file = isset($_FILES['file']) ? $_FILES['file'] : null;
    if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
        $errors = [
            UPLOAD_ERR_INI_SIZE => '文件大小超出服务器限制',
            UPLOAD_ERR_FORM_SIZE => '文件大小超出表单限制',
            UPLOAD_ERR_PARTIAL => '文件只上传了一部分',
            UPLOAD_ERR_NO_FILE => '没有文件被上传',
            UPLOAD_ERR_NO_TMP_DIR => '缺少临时目录',
            UPLOAD_ERR_CANT_WRITE => '写入磁盘失败',
            UPLOAD_ERR_EXTENSION => '文件上传被扩展阻止'
        ];
        $msg = $errors[$file['error'] ?? UPLOAD_ERR_NO_FILE] ?? '上传失败';
        echo json_encode(['code' => 400, 'msg' => $msg], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($mime, $allowedTypes, true)) {
        echo json_encode(['code' => 400, 'msg' => '不支持的文件类型'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    $maxSize = 2 * 1024 * 1024;
    if ($file['size'] > $maxSize) {
        echo json_encode(['code' => 400, 'msg' => '文件大小不能超过2MB'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    $uploadDir = dirname(__DIR__) . '/uploads/avatar/' . date('Ym') . '/';
    $saveResult = cmsStoreUploadedImage($file['tmp_name'], $file['name'], $uploadDir, 'avatar', ['apply_watermark' => false]);
    if (!$saveResult['success']) {
        echo json_encode(['code' => 400, 'msg' => $saveResult['message'] ?? '文件保存失败'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    $url = '/uploads/avatar/' . date('Ym') . '/' . $saveResult['filename'];
    echo json_encode([
        'code' => 200,
        'msg' => '上传成功',
        'url' => $url,
        'converted' => !empty($saveResult['converted'])
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

echo json_encode(['code' => 400, 'msg' => '未知操作'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
