<?php
/**
 * 炎酷CMS - 上传接口（后台通用上传 + 图片库分页）
 * POST /api/upload.php            字段名 file，返回 {code:0,msg:'ok',url,name,size}
 * GET  /api/upload.php?action=list&p=1  图片库分页 {code:0,list,total,pages}
 */
define('YKCMS', 1);
session_start();
require_once dirname(dirname(__DIR__)) . '/inc/functions.php';
require_once __DIR__ . '/upload_lib.php';

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

function yk_json($arr) {
    echo json_encode($arr, JSON_UNESCAPED_UNICODE);
    exit;
}
function yk_json_fail($msg) {
    yk_json(array('code' => 1, 'msg' => $msg));
}

// 登录态校验
if (empty($_SESSION['yk_admin_id'])) {
    yk_json_fail('未登录或登录已过期');
}

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

/* ---------------- 图片删除（图片库弹窗用，含物理文件） ---------------- */
if ($action === 'del') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        yk_json_fail('无效的请求');
    }
    if (!empty($_SESSION['yk_csrf'])) {
        $token = isset($_POST['csrf_token']) ? $_POST['csrf_token'] : '';
        if ($token === '' || !hash_equals($_SESSION['yk_csrf'], $token)) {
            yk_json_fail('CSRF 校验失败');
        }
    }
    $id  = (int)(isset($_POST['id']) ? $_POST['id'] : 0);
    $row = db_one('SELECT * FROM ' . DB_PREFIX . 'upload WHERE id = ?', array($id));
    if (!$row) {
        yk_json_fail('图片不存在');
    }
    db_exec('DELETE FROM ' . DB_PREFIX . 'upload WHERE id = ?', array($id));
    // 删除物理文件（仅允许 public/uploads/ 目录内，realpath 防穿越）
    $sitePath  = dirname(dirname(__DIR__)); // 站点根（inc/ 所在级）
    $uploadDir = realpath($sitePath . '/public/uploads');
    $filePath  = realpath($sitePath . '/public/' . ltrim($row['filepath'], '/'));
    if ($uploadDir && $filePath && strpos($filePath, $uploadDir) === 0 && is_file($filePath)) {
        @unlink($filePath);
    }
    yk_json(array('code' => 0, 'msg' => 'ok'));
}

/* ---------------- 图片库分页 ---------------- */
if ($action === 'list') {
    $page    = max(1, (int)(isset($_GET['p']) ? $_GET['p'] : 1));
    $perPage = 24;
    $total   = (int)db_val('SELECT COUNT(*) FROM ' . DB_PREFIX . 'upload');
    $pages   = max(1, (int)ceil($total / $perPage));
    $start   = ($page - 1) * $perPage;
    $rows = db_all('SELECT id, filepath, filesize, add_time FROM ' . DB_PREFIX . "upload
                    ORDER BY id DESC LIMIT $start, $perPage");
    $list = array();
    foreach ($rows as $r) {
        $list[] = array(
            'id'       => (int)$r['id'],
            'url'      => $r['filepath'],
            'name'     => basename($r['filepath']),
            'size'     => (int)$r['filesize'],
            'add_time' => (int)$r['add_time'],
        );
    }
    yk_json(array('code' => 0, 'list' => $list, 'total' => $total, 'pages' => $pages));
}

/* ---------------- 上传 ---------------- */
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['file'])) {
    yk_json_fail('无效的上传请求');
}

// CSRF：session 已发放 token 时强制校验（后台页面均会发放）
if (!empty($_SESSION['yk_csrf'])) {
    $token = isset($_POST['csrf_token']) ? $_POST['csrf_token'] : '';
    if ($token === '' || !hash_equals($_SESSION['yk_csrf'], $token)) {
        yk_json_fail('CSRF 校验失败');
    }
}

$file = $_FILES['file'];
if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK || !is_uploaded_file($file['tmp_name'])) {
    yk_json_fail('文件上传失败（错误码 ' . (isset($file['error']) ? (int)$file['error'] : -1) . '）');
}

// 大小限制
$maxBytes = yk_up_max_bytes();
if ($file['size'] <= 0 || $file['size'] > $maxBytes) {
    yk_json_fail('文件大小超出限制（最大 ' . (int)site_config('upload_max', '2') . ' MB）');
}

// 文件名 / 后缀校验（多点、黑名单、白名单）
$err = '';
$ext = yk_up_check_filename(isset($file['name']) ? $file['name'] : '', $err);
if ($ext === false) {
    yk_json_fail($err);
}

// 内容校验：必须是真实图片且 MIME 与后缀对应
if (!yk_up_check_image_content($file['tmp_name'], $ext, $err)) {
    yk_json_fail($err);
}

// 落盘 + 写库
$category = isset($_POST['category']) ? trim($_POST['category']) : '默认';
$ret = yk_up_store($file['tmp_name'], $ext, $file['name'], $category, true, $err);
if ($ret === false) {
    yk_json_fail($err);
}

yk_json(array(
    'code' => 0,
    'msg'  => 'ok',
    'url'  => $ret['url'],
    'name' => $ret['name'],
    'size' => $ret['size'],
    // 兼容旧后台 JS（读取 r.data.path）
    'data' => array('path' => $ret['url']),
));
