<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';

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

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_require_csrf_post();
mocker_admin_require_login();
mocker_admin_require_permission('site');

$f = $_FILES['logo'] ?? null;
if (!is_array($f) || (int) ($f['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
    $code = is_array($f) ? (int) ($f['error'] ?? UPLOAD_ERR_NO_FILE) : UPLOAD_ERR_NO_FILE;
    http_response_code(400);
    echo json_encode(
        ['ok' => false, 'error' => 'upload_failed', 'detail' => 'Dosya seçilmedi veya yükleme hatası (' . $code . ')'],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

$tmp = (string) ($f['tmp_name'] ?? '');
$size = (int) ($f['size'] ?? 0);
if ($tmp === '' || !is_readable($tmp) || $size <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'upload_failed', 'detail' => 'Geçersiz dosya'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($size > 3 * 1024 * 1024) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'file_too_large', 'detail' => 'Logo en fazla 3 MB olabilir.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$mime = 'application/octet-stream';
if (class_exists('finfo', false)) {
    $fi = new finfo(FILEINFO_MIME_TYPE);
    $detected = $fi->file($tmp);
    if (is_string($detected) && $detected !== '') {
        $mime = $detected;
    }
}

$extMap = [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/webp' => 'webp',
    'image/gif' => 'gif',
    'image/svg+xml' => 'svg',
];
if (!isset($extMap[$mime])) {
    http_response_code(400);
    echo json_encode(
        ['ok' => false, 'error' => 'invalid_image_type', 'detail' => 'İzin verilen: PNG, JPEG, WebP, GIF, SVG.'],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

$ext = $extMap[$mime];
$dir = dirname(__DIR__) . '/assets/gamdom';
if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'mkdir_failed'], JSON_UNESCAPED_UNICODE);
    exit;
}

foreach (glob($dir . '/logo.*') ?: [] as $old) {
    if (is_file($old)) {
        @unlink($old);
    }
}

$dest = $dir . '/logo.' . $ext;
if (!move_uploaded_file($tmp, $dest)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'save_failed', 'detail' => 'Dosya kaydedilemedi'], JSON_UNESCAPED_UNICODE);
    exit;
}

$logoUrl = '/assets/gamdom/logo.' . $ext . '?v=' . (string) time();

echo json_encode(['ok' => true, 'logoUrl' => $logoUrl], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
