<?php

declare(strict_types=1);

/**
 * BLOG 圖片上傳（Summernote；僅管理員）。
 */

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

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_blog.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_blog_upload.php';

fate_public_session_start();

$member = fate_public_member_current();
if ($member === null) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => '請先登入。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$pdo = null;
try {
    require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $pdo = $GLOBALS['pdo'];
    }
} catch (Throwable) {
    $pdo = null;
}

if (!$pdo instanceof PDO || !fate_blog_viewer_can_manage($pdo)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => '僅管理員可上傳。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$file = isset($_FILES['image']) && is_array($_FILES['image']) ? $_FILES['image'] : [];
$result = fate_blog_save_uploaded_image($file, (int) ($member['id'] ?? 0));

if (!$result['ok']) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => $result['error'] ?? '上傳失敗。'], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode([
    'ok' => true,
    'url' => (string) ($result['url'] ?? ''),
    'rel' => (string) ($result['rel'] ?? ''),
], JSON_UNESCAPED_UNICODE);
