<?php
/**
 * AJAX endpoint — instant image upload for home sections
 * Returns: { success: true, path: "/uploads/home/hero/xxx.jpg" }
 *       or { success: false, message: "..." }
 */

if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(__DIR__, 3));
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

// ── Auth guard ───────────────────────────────────────────────────────────────
if (
    empty($_SESSION['admin_logged_in']) ||
    $_SESSION['admin_logged_in'] !== true ||
    empty($_SESSION['admin_id'])
) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// ── CSRF check ───────────────────────────────────────────────────────────────
$csrfHeader = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? $_SERVER['HTTP_X_CSRF'] ?? '';
$csrfPost   = $_POST['_csrf'] ?? '';
$csrfToken  = trim($csrfHeader ?: $csrfPost);

if (
    $csrfToken === '' ||
    empty($_SESSION['_csrf']) ||
    !hash_equals((string) $_SESSION['_csrf'], $csrfToken)
) {
    http_response_code(419);
    echo json_encode(['success' => false, 'message' => 'CSRF token mismatch']);
    exit;
}

// ── Autoloader ───────────────────────────────────────────────────────────────
spl_autoload_register(function ($class) {
    $class   = ltrim($class, '\\');
    $relPath = str_replace('\\', '/', $class) . '.php';
    $relPath = str_replace(
        ['Core/', 'System/', 'App/'],
        ['core/', 'system/', 'app/'],
        $relPath
    );
    $file = ROOT_PATH . '/' . $relPath;
    if (is_file($file)) {
        require_once $file;
    }
});

require_once ROOT_PATH . '/core/system/Env.php';
\Core\System\Env::bootstrap(ROOT_PATH);

// ── Handle upload ─────────────────────────────────────────────────────────────
try {
    $allowed = ['hero', 'ads'];
    $dir     = trim($_POST['dir'] ?? 'hero');

    if (!in_array($dir, $allowed, true)) {
        throw new \RuntimeException('Invalid directory.');
    }

    if (empty($_FILES['image']) || $_FILES['image']['error'] === UPLOAD_ERR_NO_FILE) {
        throw new \RuntimeException('No file received.');
    }

    $uploadService = new \Core\App\Services\UploadService(
        ROOT_PATH . '/uploads',
        '/uploads'
    );

    $path = $uploadService->storeImage($_FILES['image'], 'home/' . $dir);

    echo json_encode(['success' => true, 'path' => $path]);

} catch (\Throwable $e) {
    http_response_code(422);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
