<?php
require_once 'db.php';

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

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

$mockupDir = 'assets/mockups/';
$mockupsToShow = [];

// ✅ Include PNG, JPG, and JPEG files
$allFiles = array_merge(
    glob($mockupDir . '*.png'),
    glob($mockupDir . '*.jpg'),
    glob($mockupDir . '*.jpeg')
);

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

// ✅ Filtering logic: show user’s mockups or global ones that don’t start with numeric prefix
foreach ($allFiles as $filePath) {
    $filename = basename($filePath);

    if (strpos($filename, $userPrefix) === 0) {
        // User-specific mockups
        $mockupsToShow[] = $filePath;
    } elseif (!preg_match('/^\d+_/', $filename)) {
        // Global mockups (don’t start with a number + underscore)
        $mockupsToShow[] = $filePath;
    }
}

// ✅ Sort filenames
sort($mockupsToShow);

// ✅ Output HTML
$saved = $_GET['saved'] ?? '';

foreach ($mockupsToShow as $mockupPath) {
    $filename = basename($mockupPath);
    $isChecked = ($filename === $saved) ? 'checked' : '';
    echo '
    <div class="col-6 col-md-3 text-center mb-3">
        <input type="radio" class="btn-check" name="mockup_filename" id="mockup_' . htmlspecialchars($filename) . '" value="' . htmlspecialchars($filename) . '" autocomplete="off" ' . $isChecked . '>
        <label class="mockup-label" for="mockup_' . htmlspecialchars($filename) . '">
            <img src="' . $mockupDir . $filename . '" class="img-fluid mockup-thumb">
        </label>
    </div>';
}
?>
