<?php
require_once 'db.php';

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

$loggedInUser = $_SESSION['logged_in_user'] ?? null;
if (!$loggedInUser) {
    exit;
}

$backgroundDir = 'assets/backgrounds/';
$backgroundsToShow = [];

$allFiles = glob($backgroundDir . '*.jpg');
$safeUserId = preg_replace('/[^a-zA-Z0-9_\-]/', '', $loggedInUser);
$userPrefix = $safeUserId . '_';

// Filter backgrounds: allow global (bg*) and current user's uploads (e.g., edkeyte_*)
foreach ($allFiles as $filePath) {
    $filename = basename($filePath);
    if (strpos($filename, 'bg') === 0 || strpos($filename, $userPrefix) === 0) {
        $backgroundsToShow[] = $filePath;
    }
}

// Output allowed backgrounds
foreach ($backgroundsToShow as $bgPath) {
    $filename = basename($bgPath);
    echo '
    <label class="background-option text-center">
        <input type="radio" name="background" value="' . htmlspecialchars($filename) . '" class="d-none">
        <img src="' . $backgroundDir . $filename . '" alt="' . $filename . '" class="img-fluid">
    </label>';
}
