<?php require_once __DIR__ . '/../layout/header.php'; ?>

<?php
// Helper: resolve a usable public image URL for a class, with sensible fallbacks.
function resolve_class_image(?string $img, ?string $name = null): string
{
    static $cache = [];
    if (isset($cache[$img])) return $cache[$img];

    $docRoot = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);

    $img = trim((string)($img ?? ''));

    // normalize any "/public/..." or "public/..." stored paths to a plain filename
    if ($img !== '') {
        $img = preg_replace('#^/?public/#', '', ltrim($img, '/'));
    }

    $candidates = [];

    if ($img !== '') {
        // if absolute path provided, try as-is and also with /public prefix
        if (strpos($img, '/') === 0) {
            $candidates[] = $img;
            $candidates[] = '/public' . $img;
        } else {
            // relative filename -> try uploads locations and root
            $candidates[] = '/public' . $img;
            $candidates[] = '/public/uploads/' . $img;
            $candidates[] = '/' . $img;
        }
    }

    // defaults by class name (use your assets folder names)
    $defaults = [
        'yoga flow'    => '/public/yoga.jfif',
        'hiit blast'   => '/public/fits.avif',
        'pilates core' => '/public/pilates.webp',
    ];

    $key = strtolower(trim((string)$name));
    if ($key !== '' && isset($defaults[$key])) {
        $candidates[] = $defaults[$key];
    }

    // common fallbacks
    $candidates[] = '/public/default-class.jpg';

    // Check each candidate against the filesystem; return the first that exists.
    foreach ($candidates as $cand) {
        if ($cand === '') {
            continue;
        }
        $full = $docRoot . $cand;
        if (file_exists($full) && is_file($full)) {
            // If the file lives under the public/ folder, return an app-aware asset URL
            if (preg_match('#^/public/(.+)$#', $cand, $m)) {
                $result = \Tshen\asset($m[1]);
                $cache[$img] = $result;
                return $result;
            }

            // If the candidate points to /public/uploads or /uploads, map to asset uploads
            if (preg_match('#^/(?:public/)?uploads/(.+)$#', $cand, $m)) {
                $result = \Tshen\asset('uploads/' . $m[1]);
                $cache[$img] = $result;
                return $result;
            }

            // Otherwise, fall back to returning a raw URL-encoded path (keeps previous behavior)
            $parts = explode('/', $cand);
            $parts = array_map('rawurlencode', $parts);
            $encoded = implode('/', $parts);
            if (substr($cand, 0, 1) === '/') {
                $encoded = '/' . ltrim($encoded, '/');
            }
            $cache[$img] = $encoded;
            return $encoded;
        }
    }

    // External placeholder if nothing on disk matched
    $cache[$img] = 'https://via.placeholder.com/600x400?text=No+Image';
    return $cache[$img];
}
?>

<div class="container">
    <h2>Class Listings</h2>

    <form class="filters" method="get" action="<?= \Tshen\url('/classes') ?>">
        <label for="location">Location:</label>
        <select name="location" id="location">
            <option value="">All</option>
            <option value="central">Central</option>
            <option value="north">North</option>
            <option value="east">East</option>
            <option value="west">West</option>
            <option value="south">South</option>
        </select>

        <label for="category">Category:</label>
        <select name="category" id="category">
            <option value="">All</option>
            <option value="yoga">Yoga</option>
            <option value="pilates">Pilates</option>
            <option value="hiit">HIIT</option>
            <option value="dance">Dance</option>
            <option value="boxing">Boxing</option>
        </select>

        <button type="submit">Apply Filters</button>
    </form>

    <?php if (empty($classes)): ?>
        <p class="notice">No classes found. Try adjusting your filters.</p>
    <?php else: ?>
        <div class="card-grid">
            <?php foreach ($classes as $class): ?>
                <?php
                    // Resolve a safe image URL for this class
                    $imgSrc = resolve_class_image($class['image'] ?? '', $class['name'] ?? '');

                    // Use a relative URL so the link resolves to the same directory as this index file
                    $bookUrl = 'book.php?id=' . (int)($class['id'] ?? 0);
                ?>
                <div class="class-card">
                    <img src="<?= htmlspecialchars($imgSrc, ENT_QUOTES, 'UTF-8') ?>"
                         alt="<?= htmlspecialchars($class['name'] ?? 'Class', ENT_QUOTES, 'UTF-8') ?>"
                         class="class-image">
                    <h3><?= htmlspecialchars($class['name']) ?></h3>
                    <div class="studio-name"><?= htmlspecialchars($class['studio_name'] ?? '') ?></div>
                    <div class="credits">Credits: <?= (int)($class['credits'] ?? 0) ?></div>
                    <div class="card-actions">
                        <?php
                        $bookUrlFull = \Tshen\url('/classes/view?id=' . (int)($class['id'] ?? 0));
                        ?>
                        <?php if (!empty($_SESSION['user'])): ?>
                            <a href="<?= htmlspecialchars($bookUrlFull, ENT_QUOTES, 'UTF-8') ?>" class="book-btn">Book Now</a>
                        <?php else: ?>
                            <a href="<?= \Tshen\url('/login') ?>?redirect=<?= rawurlencode($bookUrlFull) ?>" class="book-btn">Login to Book</a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<style>
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.filters {
    margin-bottom: 30px;
    padding: 15px;
    background: transparent;
    border-radius: 8px;
}

.filters select {
    margin: 0 15px;
    padding: 8px;
    border-radius: 4px;
}

.card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
}

.class-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    overflow: hidden;
    transition: transform 0.2s;
}

.class-card:hover {
    transform: translateY(-5px);
}

.class-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
}

.class-card h3 {
    margin: 15px;
    color: #333;
}

.studio-name {
    margin: 0 15px;
    color: #666;
}

.credits {
    margin: 10px 15px;
    color: #444;
}

.card-actions {
    padding: 15px;
    display: flex;
    gap: 10px;
}

.book-btn, .edit-btn {
    padding: 8px 16px;
    border-radius: 4px;
    text-decoration: none;
    text-align: center;
    flex: 1;
}

.book-btn {
    background: #4CAF50;
    color: white;
}


.edit-btn {
    background: #2196F3;
    color: white;
}

.notice {
    text-align: center;
    padding: 20px;
    background: #f8f8f8;
    border-radius: 8px;
}
</style>

<?php require_once __DIR__ . '/../layout/footer.php'; ?>