<?php
$baseDir = __DIR__;
$allowedExt = ['mp3', 'wav', 'ogg', 'm4a'];

function getFolders(string $dir): array {
    $folders = array_filter(glob($dir . '/*'), 'is_dir');
    natsort($folders); // natural sorting
    return $folders;
}

function getAudioFiles(string $dir, array $allowedExt): array {
    $files = [];
    foreach ($allowedExt as $ext) {
        $files = array_merge($files, glob($dir . "/*.{$ext}"));
    }
    natsort($files); // natural sorting
    return $files;
}

$folders = is_dir($baseDir) ? getFolders($baseDir) : [];
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Avatar Audio Gallery</title>

    <!-- Google Font -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

    <style>
    body {
        margin: 0;
        font-family: 'Poppins', sans-serif;
        background: #f0f0f5;
        color: #333;
    }

    .page-header {
        text-align: center;
        margin-bottom: 2rem;
    }

    .page-header h1 {
        font-weight: 600;
        color: #444;
    }

    .page-header p {
        color: #777;
        margin-top: .5rem;
    }

    .avatar-card {
        border-radius: 1rem;
    }

    .avatar-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #ff6f61;
    }

    .audio-chip {
        border-radius: 999px;
        font-size: 0.8rem;
        cursor: pointer;
        transition: transform .15s ease, box-shadow .15s ease;
        background: linear-gradient(90deg, #6a11cb, #2575fc);
        color: #fff;
        border: none;
    }

    .audio-chip:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, .18);
    }

    footer {
        text-align: center;
        margin-top: 2.5rem;
        font-size: 0.8rem;
        color: #888;
    }
    </style>
</head>

<body>
    <div class="container py-5">

        <div class="page-header">
            <h1>🎧 Avatar Audios</h1>
            <p class="mb-0">Browse each avatar folder and click a track to play it instantly.</p>
        </div>

        <?php if (!is_dir($baseDir)): ?>

        <div class="alert alert-danger">
            Base directory not found.
        </div>

        <?php elseif (count($folders) === 0): ?>

        <div class="alert alert-warning">
            No subfolders found in this directory.
        </div>

        <?php else: ?>

        <div class="row g-4">
            <?php foreach ($folders as $folder): ?>
            <?php
                        $folderName   = basename($folder);
                        $displayName  = ucwords(str_replace('_', ' ', $folderName));
                        $audios       = getAudioFiles($folder, $allowedExt);
                        $audioCount   = count($audios);
                    ?>

            <div class="col-12 col-md-6">
                <div class="card shadow-sm avatar-card h-100">
                    <div class="card-body d-flex flex-column">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <div class="avatar-title">
                                <?php echo htmlspecialchars($displayName, ENT_QUOTES, 'UTF-8'); ?>
                            </div>
                            <span class="badge bg-secondary">
                                <?php echo $audioCount; ?> track<?php echo $audioCount === 1 ? '' : 's'; ?>
                            </span>
                        </div>

                        <?php if ($audioCount === 0): ?>

                        <p class="text-muted mb-0">No audio files in this folder.</p>

                        <?php else: ?>

                        <div class="d-flex flex-wrap gap-2 mb-3">
                            <?php foreach ($audios as $audio): ?>
                            <?php
                                $audioName = pathinfo($audio, PATHINFO_FILENAME);
                                $audioUrl  = basename($folder) . '/' . basename($audio);
                            ?>
                            <button type="button" class="btn btn-sm audio-chip"
                                onclick="playAudio(this, '<?php echo htmlspecialchars($audioUrl, ENT_QUOTES, 'UTF-8'); ?>')"
                                title="<?php echo htmlspecialchars($audioName, ENT_QUOTES, 'UTF-8'); ?>">
                                <?php echo htmlspecialchars($audioName, ENT_QUOTES, 'UTF-8'); ?>
                            </button>
                            <?php endforeach; ?>
                        </div>

                        <?php endif; ?>

                        <audio class="audio-player w-100 mt-auto" controls></audio>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <?php endif; ?>

        <footer class="mt-4">
            &copy; <?php echo date('Y'); ?> Avatar Audio Collection
        </footer>
    </div>

    <!-- Bootstrap JS (optional but nice for future components) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous">
    </script>

    <script>
    function playAudio(buttonEl, url) {
        // Pause all players
        document.querySelectorAll('.audio-player').forEach(player => {
            player.pause();
            player.currentTime = 0;
        });

        // Find the audio player in the same card
        const card = buttonEl.closest('.avatar-card');
        const player = card ? card.querySelector('.audio-player') : null;

        if (player) {
            if (player.src !== url) {
                player.src = url;
            }
            player.play().catch(() => {
                // Autoplay might be blocked; user can press play manually.
            });
        }
    }
    </script>
</body>

</html>