<?php
require_once 'db.php';
session_start();

$loggedInUser = $_SESSION['logged_in_user'] ?? null;

if (!$loggedInUser) {
    echo json_encode(['success' => false, 'error' => 'Not logged in']);
    exit;
}

$stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$userId = $stmt->fetchColumn();

if (!$userId) {
    echo json_encode(['success' => false, 'error' => 'Invalid user']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['background_image'])) {
    $file = $_FILES['background_image'];
    $maxSize = 400 * 1024; // 400 KB

    // Secure MIME type check
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if ($mimeType !== 'image/jpeg') {
        echo json_encode(['success' => false, 'error' => 'Only valid JPEG (.jpg) files are allowed']);
        exit;
    }

    if ($file['size'] > $maxSize) {
        echo json_encode(['success' => false, 'error' => 'File must be under 200 KB']);
        exit;
    }

    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $random = bin2hex(random_bytes(3)); // short random string
    $safeUsername = preg_replace('/[^a-zA-Z0-9_\-]/', '', $loggedInUser);

// Optional whitelist for power users who can upload more than 5
$whitelistedUsers = ['edkeyte', 'joinnow']; // Add usernames here

$isWhitelisted = in_array($loggedInUser, $whitelistedUsers);


    // Limit to 5 uploaded backgrounds per user
    $userPrefix = $safeUsername . '_';
    $existingFiles = glob(__DIR__ . "/assets/backgrounds/{$userPrefix}*.jpg");

$maxUploads = $isWhitelisted ? 10 : 5;

if (count($existingFiles) >= $maxUploads) {
    echo json_encode([
        'success' => false,
        'error' => "You have already uploaded {$maxUploads} background images. Please delete one before uploading another."
    ]);
    exit;
}


    $newFilename = "{$safeUsername}_{$random}.jpg";

    $uploadDir = __DIR__ . '/assets/backgrounds/';
    $targetPath = $uploadDir . $newFilename;

    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        echo json_encode(['success' => true, 'filename' => $newFilename]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Upload failed']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'No file uploaded']);
}
