<?php

declare(strict_types=1);

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_review_upload.php';

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

fate_public_session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => '不支援的請求'], JSON_UNESCAPED_UNICODE);
    exit;
}

$member = fate_public_member_current();
$memberId = is_array($member) ? (int) ($member['id'] ?? 0) : 0;

$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 || $memberId <= 0 || !fate_public_member_can_interact($pdo)) {
    http_response_code(403);
    echo json_encode([
        'ok' => false,
        'error' => $pdo instanceof PDO ? fate_public_member_interact_denied_message($pdo) : '請先登入並完成 Email 驗證',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}
if (!fate_public_member_csrf_check(isset($_POST['csrf']) ? (string) $_POST['csrf'] : null)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => '安全驗證失敗'], JSON_UNESCAPED_UNICODE);
    exit;
}

$file = isset($_FILES['image']) && is_array($_FILES['image']) ? $_FILES['image'] : [];
$res = fate_review_image_save_uploaded_file($file, $memberId);

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

echo json_encode([
    'ok' => true,
    'url' => (string) ($res['url'] ?? ''),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
