<?php
require __DIR__.'/auth.php';
$isLoggedIn = isLoggedIn();
$isUser = !empty($_SESSION['user_id']);

$tracks = [];
$allGenres = [];
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = @new mysqli(env('DB_HOST','localhost'),env('DB_USER','websiteuser'),env('DB_PASS','starkesPasswort123'),env('DB_NAME','website'),env('DB_PORT',3306));
if (!$mysqli->connect_errno) {
  $mysqli->set_charset('utf8mb4');
  $q = "SELECT id, slug, title, description_text, play_url, cover_url, duration_seconds, recorded_at, location_text, genres_csv
        FROM music_tracks
        WHERE is_active=1
        ORDER BY COALESCE(sort_date, recorded_at, created_at) DESC, id DESC
        LIMIT 50";
  if ($res = $mysqli->query($q)) { 
    while ($row = $res->fetch_assoc()) { 
      $tracks[] = $row;
      $genres = array_filter(array_map('trim', explode(',', $row['genres_csv'] ?? '')));
      foreach($genres as $g) { $allGenres[$g] = true; }
    } 
    $res->free(); 
  }
}
$allGenres = array_keys($allGenres);
sort($allGenres);
?>
<!DOCTYPE html>
<html lang="de">
<head>
<link rel="icon" type="image/png" href="/tribevibe_90x90.png">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="description" content="TribeVibe Events Music - Höre die besten Techno und Hard Techno Sets aus Nürnberg.">
<title>Music – TribeVibe Events</title>
<link href="templatemo-nexus-style.css" rel="stylesheet">
<link href="assets/custom.css" rel="stylesheet">
<style>
:root{--tile-w:280px;--tile-gap:18px;--tile-pad:16px;--cover-max-h:200px;--radius:16px}

.music-filters{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:1.5rem;align-items:center}
.search-box{position:relative;flex:1;min-width:200px;max-width:400px}
.search-input{width:100%;padding:.75rem 1rem .75rem 2.5rem;background:rgba(0,0,0,.4);border:1px solid rgba(255,255,255,.1);border-radius:12px;color:#eef1f7;font-size:.95rem;transition:border-color .2s ease,box-shadow .2s ease}
.search-input:focus{outline:none;border-color:var(--primary-cyan);box-shadow:0 0 0 3px rgba(70,230,255,.15)}
.search-input::placeholder{color:rgba(255,255,255,.4)}
.search-icon{position:absolute;left:.85rem;top:50%;transform:translateY(-50%);opacity:.5;pointer-events:none}

.genre-filters{display:flex;gap:8px;flex-wrap:wrap}
.genre-btn{padding:.45rem .75rem;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.1);border-radius:8px;color:#a7adbd;font-size:.8rem;cursor:pointer;transition:all .2s ease}
.genre-btn:hover{background:rgba(70,230,255,.1);border-color:rgba(70,230,255,.2);color:var(--primary-cyan)}
.genre-btn.active{background:rgba(70,230,255,.15);border-color:var(--primary-cyan);color:var(--primary-cyan)}

.music-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(var(--tile-w),1fr));gap:var(--tile-gap)}
.music-card{background:rgba(0,0,0,.35);backdrop-filter:saturate(140%) blur(6px);border:1px solid rgba(255,255,255,.08);border-radius:var(--radius);padding:var(--tile-pad);box-shadow:0 12px 28px rgba(0,0,0,.3);transition:transform .12s ease,box-shadow .25s ease,border-color .25s ease}
.music-card:hover{transform:translateY(-3px);box-shadow:0 18px 36px rgba(0,0,0,.35);border-color:rgba(105,255,227,.3)}
.music-card.hidden{display:none}

.cover-frame{width:100%;display:flex;align-items:center;justify-content:center;background:#0b1412;border-radius:12px;margin-bottom:14px;overflow:hidden;border:1px solid rgba(255,255,255,.06);padding:8px;aspect-ratio:1/1}
.cover{display:block;width:100%;height:100%;object-fit:cover;object-position:center;border-radius:8px}
.no-cover{display:flex;align-items:center;justify-content:center;width:100%;height:100%;background:linear-gradient(135deg,rgba(70,230,255,.1),rgba(138,109,255,.1));border-radius:8px;font-size:3rem;color:var(--primary-cyan);opacity:.5}

.music-card h3{font-size:1.05rem;margin:.25rem 0 .4rem 0;line-height:1.3}
.music-card .meta{opacity:.7;font-size:.82em;margin-bottom:.4rem;line-height:1.4}
.music-card .tags{display:flex;flex-wrap:wrap;gap:6px;margin:.6rem 0}
.tag{display:inline-block;padding:.22rem .5rem;background:rgba(70,230,255,.08);border:1px solid rgba(70,230,255,.15);border-radius:6px;font-size:.72rem;color:var(--primary-cyan);cursor:pointer;transition:all .2s ease}
.tag:hover{background:rgba(70,230,255,.15);border-color:rgba(70,230,255,.3)}
.music-card p{font-size:.88rem;opacity:.85;margin:.4rem 0 .9rem 0;line-height:1.45}

.audio-player{background:rgba(0,0,0,.3);border:1px solid rgba(255,255,255,.08);border-radius:12px;padding:12px;margin-top:.5rem}
.player-controls{display:flex;align-items:center;gap:10px}
.play-pause-btn{width:40px;height:40px;border-radius:50%;background:linear-gradient(135deg,var(--primary-cyan),var(--primary-pink));border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:transform .15s ease,box-shadow .2s ease;box-shadow:0 4px 12px rgba(70,230,255,.25)}
.play-pause-btn:hover{transform:scale(1.05);box-shadow:0 6px 18px rgba(70,230,255,.35)}
.play-pause-btn svg{width:16px;height:16px;fill:#00130f}
.progress-container{flex:1;height:6px;background:rgba(255,255,255,.1);border-radius:3px;cursor:pointer;position:relative;overflow:hidden}
.progress-bar{height:100%;background:linear-gradient(90deg,var(--primary-cyan),var(--primary-pink));border-radius:3px;width:0%;transition:width .1s linear}
.time-display{font-size:.75rem;color:rgba(255,255,255,.6);min-width:80px;text-align:right}

.play-link{display:inline-flex;align-items:center;justify-content:center;gap:.5rem;padding:.55rem .95rem;border-radius:10px;border:1px solid rgba(255,255,255,.12);text-decoration:none;color:#eef1f7;background:linear-gradient(180deg,rgba(255,255,255,.06),rgba(255,255,255,.02));transition:transform .1s ease,border-color .2s ease,box-shadow .2s ease}
.play-link:hover{transform:translateY(-2px);border-color:var(--primary-cyan);box-shadow:0 8px 20px rgba(70,230,255,.2)}

.no-results{grid-column:1/-1;text-align:center;padding:3rem 1rem;opacity:.7}
.no-results h3{margin-bottom:.5rem}

@media (max-width:640px){
  :root{--tile-w:260px;--cover-max-h:180px}
  .music-filters{flex-direction:column}
  .search-box{max-width:none}
}
</style>
</head>
<body id="top">
<?php include __DIR__.'/includes/background.php'; ?>
<?php include __DIR__.'/includes/nav.php'; ?>

<section class="page-hero"><h1>Music</h1></section>

<section class="section">
  <div class="container">
    <div class="music-filters">
      <div class="search-box">
        <svg class="search-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/>
        </svg>
        <input type="text" class="search-input" id="musicSearch" placeholder="Sets durchsuchen..." autocomplete="off">
      </div>
      <?php if(count($allGenres) > 0): ?>
      <div class="genre-filters" id="genreFilters">
        <button type="button" class="genre-btn active" data-genre="all">Alle</button>
        <?php foreach($allGenres as $g): ?>
          <button type="button" class="genre-btn" data-genre="<?php echo htmlspecialchars($g, ENT_QUOTES, 'UTF-8'); ?>">
            <?php echo htmlspecialchars($g, ENT_QUOTES, 'UTF-8'); ?>
          </button>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

    <div class="music-grid" id="musicGrid">
      <?php if (!count($tracks)): ?>
        <div class="music-card"><h3>Coming soon</h3><p>Gerade noch keine Uploads. Schaue eventuell nochmal vorbei, wenn die nächste Rave war.</p></div>
      <?php else: foreach ($tracks as $t):
        $titleRaw = $t['title'] ?? '';
        $title = htmlspecialchars($titleRaw, ENT_QUOTES, 'UTF-8');
        $titleSearch = htmlspecialchars(mb_strtolower($titleRaw, 'UTF-8'), ENT_QUOTES, 'UTF-8');
        $desc  = htmlspecialchars($t['description_text'] ?? '', ENT_QUOTES, 'UTF-8');
        $play  = htmlspecialchars($t['play_url'] ?? '', ENT_QUOTES, 'UTF-8');
        $cover = htmlspecialchars($t['cover_url'] ?? '', ENT_QUOTES, 'UTF-8');
        $genres = array_filter(array_map('trim', explode(',', $t['genres_csv'] ?? '')));
        $genresJson = htmlspecialchars(json_encode($genres), ENT_QUOTES, 'UTF-8');

        if ($cover) {
          if (!preg_match('~^https?://~', $cover)) {
            if (str_starts_with($cover, '/admin/')) {
              $cover = 'https://admin.tribevibeevents.de' . $cover;
            } else {
              $cover = 'https://tribevibe.de' . $cover;
            }
          }
        }

        $loc   = htmlspecialchars($t['location_text'] ?? '', ENT_QUOTES, 'UTF-8');
        $recAt = !empty($t['recorded_at']) ? date('d.m.Y', strtotime($t['recorded_at'])) : '';
        $dur   = !empty($t['duration_seconds']) ? floor($t['duration_seconds']/60).'m '.($t['duration_seconds']%60).'s' : '';
        $meta  = trim(($recAt?$recAt:'').($loc?(' • '.$loc):'').($dur?(' • '.$dur):''));
        
        $isAudioFile = preg_match('/\.(mp3|wav|ogg|m4a|flac|aac)$/i', $play);
      ?>
      <div class="music-card" data-title="<?php echo $titleSearch; ?>" data-genres="<?php echo $genresJson; ?>">
        <div class="cover-frame">
          <?php if ($cover): ?>
            <img class="cover" src="<?php echo $cover; ?>" alt="<?php echo $title; ?>" loading="lazy" decoding="async">
          <?php else: ?>
            <div class="no-cover">♫</div>
          <?php endif; ?>
        </div>
        <h3><?php echo $title; ?></h3>
        <?php if ($meta): ?><div class="meta"><?php echo $meta; ?></div><?php endif; ?>
        <?php if (count($genres)): ?>
          <div class="tags">
            <?php foreach ($genres as $g): ?>
              <span class="tag" data-filter-genre="<?php echo htmlspecialchars($g, ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($g, ENT_QUOTES, 'UTF-8'); ?></span>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
        <?php if ($desc): ?><p><?php echo $desc; ?></p><?php endif; ?>
        
        <?php if ($play): ?>
          <?php if ($isAudioFile): ?>
            <div class="audio-player" data-src="<?php echo $play; ?>">
              <div class="player-controls">
                <button type="button" class="play-pause-btn" aria-label="Play/Pause">
                  <svg class="icon-play" viewBox="0 0 24 24"><polygon points="5,3 19,12 5,21"/></svg>
                  <svg class="icon-pause" viewBox="0 0 24 24" style="display:none"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
                </button>
                <div class="progress-container">
                  <div class="progress-bar"></div>
                </div>
                <span class="time-display">0:00 / 0:00</span>
              </div>
            </div>
          <?php else: ?>
            <a href="<?php echo $play; ?>" class="play-link" target="_blank" rel="noopener">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><polygon points="5,3 19,12 5,21"/></svg>
              Play
            </a>
          <?php endif; ?>
        <?php endif; ?>
      </div>
      <?php endforeach; endif; ?>
      
      <div class="no-results" id="noResults" style="display:none">
        <h3>Keine Sets gefunden</h3>
        <p>Versuche andere Suchbegriffe oder Filter.</p>
      </div>
    </div>
  </div>
</section>

<?php include __DIR__.'/includes/footer.php'; ?>

<script src="temlatemo-nexus-scripts.js"></script>
<script src="assets/site.js"></script>
<script>
(function(){
  var searchInput = document.getElementById('musicSearch');
  var genreFilters = document.getElementById('genreFilters');
  var musicGrid = document.getElementById('musicGrid');
  var noResults = document.getElementById('noResults');
  var cards = musicGrid ? Array.from(musicGrid.querySelectorAll('.music-card[data-title]')) : [];
  var currentGenre = 'all';
  var currentSearch = '';

  function filterCards(){
    var visibleCount = 0;
    cards.forEach(function(card){
      var title = card.getAttribute('data-title') || '';
      var genres = [];
      try { genres = JSON.parse(card.getAttribute('data-genres') || '[]'); } catch(e){}
      
      var matchSearch = !currentSearch || title.indexOf(currentSearch) !== -1;
      var matchGenre = currentGenre === 'all' || genres.map(function(g){ return g.toLowerCase(); }).indexOf(currentGenre.toLowerCase()) !== -1;
      
      if(matchSearch && matchGenre){
        card.classList.remove('hidden');
        visibleCount++;
      } else {
        card.classList.add('hidden');
      }
    });
    
    if(noResults) noResults.style.display = visibleCount === 0 && cards.length > 0 ? 'block' : 'none';
  }

  if(searchInput){
    searchInput.addEventListener('input', function(){
      currentSearch = this.value.toLowerCase().trim();
      filterCards();
    });
  }

  if(genreFilters){
    genreFilters.addEventListener('click', function(e){
      var btn = e.target.closest('.genre-btn');
      if(!btn) return;
      
      genreFilters.querySelectorAll('.genre-btn').forEach(function(b){ b.classList.remove('active'); });
      btn.classList.add('active');
      currentGenre = btn.getAttribute('data-genre') || 'all';
      filterCards();
    });
  }

  document.querySelectorAll('.tag[data-filter-genre]').forEach(function(tag){
    tag.addEventListener('click', function(){
      var genre = this.getAttribute('data-filter-genre');
      if(genreFilters){
        var btn = genreFilters.querySelector('[data-genre="' + genre + '"]');
        if(btn) btn.click();
      }
    });
  });

  var currentAudio = null;
  var currentPlayer = null;

  document.querySelectorAll('.audio-player').forEach(function(player){
    var src = player.getAttribute('data-src');
    var playBtn = player.querySelector('.play-pause-btn');
    var iconPlay = player.querySelector('.icon-play');
    var iconPause = player.querySelector('.icon-pause');
    var progressBar = player.querySelector('.progress-bar');
    var progressContainer = player.querySelector('.progress-container');
    var timeDisplay = player.querySelector('.time-display');
    var audio = null;

    function formatTime(seconds){
      var mins = Math.floor(seconds / 60);
      var secs = Math.floor(seconds % 60);
      return mins + ':' + (secs < 10 ? '0' : '') + secs;
    }

    function updateProgress(){
      if(audio && audio.duration){
        var pct = (audio.currentTime / audio.duration) * 100;
        progressBar.style.width = pct + '%';
        timeDisplay.textContent = formatTime(audio.currentTime) + ' / ' + formatTime(audio.duration);
      }
    }

    function togglePlay(){
      if(!audio){
        audio = new Audio(src);
        audio.addEventListener('timeupdate', updateProgress);
        audio.addEventListener('loadedmetadata', function(){
          timeDisplay.textContent = '0:00 / ' + formatTime(audio.duration);
        });
        audio.addEventListener('ended', function(){
          iconPlay.style.display = '';
          iconPause.style.display = 'none';
          progressBar.style.width = '0%';
          audio.currentTime = 0;
        });
      }

      if(currentAudio && currentAudio !== audio){
        currentAudio.pause();
        if(currentPlayer){
          currentPlayer.querySelector('.icon-play').style.display = '';
          currentPlayer.querySelector('.icon-pause').style.display = 'none';
        }
      }

      if(audio.paused){
        audio.play();
        iconPlay.style.display = 'none';
        iconPause.style.display = '';
        currentAudio = audio;
        currentPlayer = player;
      } else {
        audio.pause();
        iconPlay.style.display = '';
        iconPause.style.display = 'none';
      }
    }

    playBtn.addEventListener('click', togglePlay);

    progressContainer.addEventListener('click', function(e){
      if(!audio || !audio.duration) return;
      var rect = progressContainer.getBoundingClientRect();
      var pct = (e.clientX - rect.left) / rect.width;
      audio.currentTime = pct * audio.duration;
    });
  });
})();
</script>
</body>
</html>
