<?php
require_once __DIR__ . '/common.php';
require_once __DIR__ . '/includes/debug-log.php';
header('Content-Type: application/json; charset=utf-8');

function upload_fail(string $message, int $errno = 1): void
{
    blog_debug_log('upload_image.log', [
        'event' => 'fail',
        'uid' => (int)(current_user_id() ?: 0),
        'errno' => $errno,
        'message' => blog_debug_preview($message),
        'file_name' => isset($_FILES['file']['name']) ? blog_debug_preview((string)$_FILES['file']['name']) : null,
        'file_size' => isset($_FILES['file']['size']) ? (int)$_FILES['file']['size'] : null,
        'file_error' => isset($_FILES['file']['error']) ? (int)$_FILES['file']['error'] : null,
    ]);
    echo json_encode([
        'errno' => $errno,
        'message' => $message,
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    upload_fail('Method not allowed');
}

$token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ($_POST['csrf_token'] ?? '');
if (!csrf_check($token)) {
    upload_fail('CSRF validation failed');
}

if (!current_user_id()) {
    upload_fail('Please login');
}

if (is_ip_blacklisted()) {
    upload_fail('Current IP is blocked');
}

if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
    upload_fail('No file received');
}

$file = $_FILES['file'];
if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
    upload_fail('Upload failed (error code: ' . (int)($file['error'] ?? -1) . ')');
}

$maxSize = 2 * 1024 * 1024;
if (($file['size'] ?? 0) > $maxSize) {
    upload_fail('Image size must be <= 2MB');
}

$ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
$allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
if (!in_array($ext, $allowedExt, true)) {
    upload_fail('Only JPG / PNG / GIF / WEBP allowed');
}

$tmpPath = $file['tmp_name'] ?? '';
if ($tmpPath === '' || !is_uploaded_file($tmpPath)) {
    upload_fail('Temporary file not available');
}

$mimeOk = false;
$mime = '';
if (function_exists('finfo_open')) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    if ($finfo) {
        $mime = finfo_file($finfo, $tmpPath);
        finfo_close($finfo);
        if (in_array($mime, ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], true)) {
            $mimeOk = true;
        }
    }
}

if (!$mimeOk) {
    $info = @getimagesize($tmpPath);
    if ($info) {
        $types = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF];
        if (defined('IMAGETYPE_WEBP')) {
            $types[] = IMAGETYPE_WEBP;
        }
        if (in_array($info[2], $types, true)) {
            $mimeOk = true;
            if ($mime === '' && isset($info['mime'])) {
                $mime = (string)$info['mime'];
            }
        }
    }
}

if (!$mimeOk) {
    upload_fail('Invalid image file');
}

$dir = BASE_PATH . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'editor_images';
if (!is_dir($dir)) {
    @mkdir($dir, 0777, true);
}

$uid = (int)current_user_id();
$filename = 'img' . $uid . '_' . date('YmdHis') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
$target = $dir . DIRECTORY_SEPARATOR . $filename;

if (!@move_uploaded_file($tmpPath, $target)) {
    upload_fail('Failed to save image');
}

$url = '/uploads/editor_images/' . $filename;

record_media_file(
    'image',
    $url,
    (string)($file['name'] ?? ''),
    (int)($file['size'] ?? 0),
    (string)$mime,
    $uid
);

if (session_status() === PHP_SESSION_ACTIVE) {
    if (!isset($_SESSION['recent_uploads']) || !is_array($_SESSION['recent_uploads'])) {
        $_SESSION['recent_uploads'] = [];
    }
    $_SESSION['recent_uploads'][] = [
        'type' => 'image',
        'url' => $url,
        'uid' => $uid,
        'time' => time(),
    ];
    if (count($_SESSION['recent_uploads']) > 50) {
        $_SESSION['recent_uploads'] = array_slice($_SESSION['recent_uploads'], -50);
    }

    $_SESSION['last_upload_url'] = $url;
    $_SESSION['last_upload_time'] = time();
    $_SESSION['last_upload_uid'] = $uid;
}

blog_debug_log('upload_image.log', [
    'event' => 'ok',
    'uid' => $uid,
    'url' => $url,
    'original_name' => blog_debug_preview((string)($file['name'] ?? '')),
    'size' => (int)($file['size'] ?? 0),
    'mime' => (string)$mime,
]);

echo json_encode([
    'errno' => 0,
    'data' => [
        'url' => $url,
        'alt' => '',
        'href' => '',
    ],
], JSON_UNESCAPED_UNICODE);
