<?php
require __DIR__ . '/config/config.php';

try {
    $db = new PDO('sqlite:' . DB_PATH);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("
        CREATE TABLE IF NOT EXISTS stream_metadata (
            stream_id INTEGER PRIMARY KEY,
            station_id INTEGER,
            title TEXT,
            artist TEXT,
            raw TEXT,
            fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    ");

    $stations = $db->query("
        SELECT s.*,
               (SELECT id FROM streams WHERE station_id=s.id AND active=1 ORDER BY priority LIMIT 1) AS stream_id,
               (SELECT url FROM streams WHERE station_id=s.id AND active=1 ORDER BY priority LIMIT 1) AS stream_url,
               (SELECT online FROM stream_status ss
                JOIN streams st ON st.id=ss.stream_id
                WHERE st.station_id=s.id AND st.active=1 ORDER BY st.priority LIMIT 1) AS is_online,
               m.title AS meta_title, m.artist AS meta_artist
        FROM stations s
        LEFT JOIN metadata m ON m.station_id=s.id
        WHERE s.active=1
        ORDER BY s.sort_order, s.name
    ")->fetchAll(PDO::FETCH_ASSOC);

    $streamRows = $db->query("
        SELECT st.id, st.station_id, st.url, st.label, st.format, st.bitrate, st.priority,
               sm.title AS meta_title, sm.artist AS meta_artist, sm.raw AS meta_raw
        FROM streams st
        LEFT JOIN stream_metadata sm ON sm.stream_id=st.id
        WHERE st.active=1
        ORDER BY st.station_id, st.priority, st.label
    ")->fetchAll(PDO::FETCH_ASSOC);

    $streamsByStation = [];
    foreach ($streamRows as $streamRow) {
        $streamsByStation[(int)$streamRow['station_id']][] = $streamRow;
    }
} catch (Exception $e) {
    die('<p style="color:red;padding:20px">Databasen hittades inte – kör <a href="install.php">install.php</a> först.</p>');
}

$genres = array_unique(array_filter(array_column($stations, 'genre')));
sort($genres);

$isEmbeddedApp = isset($_GET['appv']);

function playbackUrl(?string $url, ?int $streamId): string {
    if (!$url) {
        return '';
    }
    if (stripos($url, 'http://') === 0 && $streamId) {
        return 'stream.php?id=' . (int)$streamId;
    }
    return $url;
}

function firstDownloadOption(array $filenames): ?array {
    foreach ($filenames as $filename) {
        $path = __DIR__ . '/downloads/' . $filename;
        if (is_file($path)) {
            return [
                'filename' => $filename,
                'url' => 'downloads/' . rawurlencode($filename) . '?v=' . filemtime($path),
            ];
        }
    }

    return null;
}

$androidDownload = firstDownloadOption(['radio-engfeldt.apk']);
$windowsDownload = firstDownloadOption([
    'radio-engfeldt.exe',
    'radio-engfeldt.msi',
    'radio-engfeldt.msix',
    'radio-engfeldt.msixbundle',
    'radio-engfeldt.appinstaller',
    'radio-engfeldt.zip',
]);
$macDownload = firstDownloadOption([
    'radio-engfeldt.dmg',
    'radio-engfeldt.pkg',
    'radio-engfeldt-macos.zip',
]);
$linuxDownload = firstDownloadOption([
    'radio-engfeldt.AppImage',
    'radio-engfeldt.deb',
    'radio-engfeldt.rpm',
    'radio-engfeldt-linux.tar.gz',
    'radio-engfeldt-linux.zip',
]);
?>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#0f0f1a">
<title>🎙️ Radio Engfeldt</title>
<link rel="stylesheet" href="assets/css/style.css?v=<?php echo filemtime(__DIR__ . '/assets/css/style.css'); ?>">
<link rel="icon" type="image/svg+xml" href="assets/icons/favicon.svg?v=<?php echo filemtime(__DIR__ . '/assets/icons/favicon.svg'); ?>">
<link rel="icon" type="image/x-icon" href="assets/icons/radio-engfeldt.ico">
<link rel="apple-touch-icon" href="assets/icons/apple-touch-icon.png">
<link rel="manifest" href="/manifest.json">
</head>
<body>
<header class="site-header">
  <div class="header-inner">
    <div class="logo-area">
      <span class="logo-icon">🎙️</span>
      <div>
        <h1>Radio Engfeldt
          <?php if (!$isEmbeddedApp): ?>
          <span class="app-download-menu" data-app-download-menu>
            <button class="app-download-toggle" type="button" id="appDownloadButton" aria-haspopup="true" aria-expanded="false">
              <span data-app-download-label>Nedladdning enheter</span>
              <span class="app-download-chevron">▾</span>
            </button>
            <span class="app-download-options" role="menu" aria-labelledby="appDownloadButton">
              <?php if ($androidDownload): ?>
              <a class="app-download-option" role="menuitem" href="<?= htmlspecialchars($androidDownload['url']) ?>" download="<?= htmlspecialchars($androidDownload['filename']) ?>" type="application/vnd.android.package-archive" data-platform="android" data-preferred-label="Installera Android-app">
                <strong>Android</strong>
                <span>APK för Android-telefoner och surfplattor</span>
              </a>
              <?php endif; ?>
              <?php if ($windowsDownload): ?>
              <a class="app-download-option" role="menuitem" href="<?= htmlspecialchars($windowsDownload['url']) ?>" download="<?= htmlspecialchars($windowsDownload['filename']) ?>" data-platform="windows" data-preferred-label="Ladda ner Windows-app">
                <strong>Windows</strong>
                <span>Installationsfil för Windows-datorer</span>
              </a>
              <?php else: ?>
              <a class="app-download-option" role="menuitem" href="./" data-platform="windows" data-preferred-label="Använd i webbläsaren">
                <strong>Windows</strong>
                <span>Använd webbsidan i Windows</span>
              </a>
              <?php endif; ?>
              <?php if ($macDownload): ?>
              <a class="app-download-option" role="menuitem" href="<?= htmlspecialchars($macDownload['url']) ?>" download="<?= htmlspecialchars($macDownload['filename']) ?>" data-platform="mac" data-preferred-label="Ladda ner Mac-app">
                <strong>Mac</strong>
                <span>Installationsfil för macOS</span>
              </a>
              <?php else: ?>
              <a class="app-download-option" role="menuitem" href="./" data-platform="mac" data-preferred-label="Använd i webbläsaren">
                <strong>Mac</strong>
                <span>Använd webbsidan i macOS</span>
              </a>
              <?php endif; ?>
              <?php if ($linuxDownload): ?>
              <a class="app-download-option" role="menuitem" href="<?= htmlspecialchars($linuxDownload['url']) ?>" download="<?= htmlspecialchars($linuxDownload['filename']) ?>" data-platform="linux" data-preferred-label="Ladda ner Linux-app">
                <strong>Linux</strong>
                <span>Installationsfil för Linux</span>
              </a>
              <?php else: ?>
              <a class="app-download-option" role="menuitem" href="./" data-platform="linux" data-preferred-label="Använd i webbläsaren">
                <strong>Linux</strong>
                <span>Använd webbsidan i Linux</span>
              </a>
              <?php endif; ?>
              <a class="app-download-option" role="menuitem" href="./" data-platform="ios" data-preferred-label="Använd i webbläsaren">
                <strong>iPhone/iPad</strong>
                <span>Använd webbsidan i Safari</span>
              </a>
              <a class="app-download-option" role="menuitem" href="./" data-platform="web" data-preferred-label="Använd i webbläsaren">
                <strong>Övriga enheter</strong>
                <span>Använd webbsidan i webbläsaren</span>
              </a>
            </span>
          </span>
          <?php endif; ?>
        </h1>
        <p class="tagline">Dina svenska radiokanaler</p>
      </div>
    </div>
    <div class="header-controls">
      <div class="search-wrap">
        <input type="text" id="search" placeholder="Sök kanal…" autocomplete="off">
      </div>
      <div class="genre-filter" id="genreFilter">
        <button class="chip active" data-genre="">Alla</button>
        <?php foreach ($genres as $g): ?>
        <button class="chip" data-genre="<?= htmlspecialchars($g) ?>"><?= htmlspecialchars($g) ?></button>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</header>

<!-- Sticky Player -->
<div class="sticky-player" id="stickyPlayer" style="display:none">
  <div class="player-inner">
    <div class="player-logo">
      <img id="playerLogo" src="" alt="" onerror="this.style.display='none'">
      <span id="playerLogoFallback" class="logo-fallback"></span>
    </div>
    <div class="player-info">
      <span class="player-name" id="playerName">–</span>
      <span class="player-meta" id="playerMeta"></span>
    </div>
    <div class="player-controls">
      <button class="btn-play-main" id="btnPlay" title="Play/Pause">▶</button>
      <div class="volume-wrap">
        <span>🔊</span>
        <input type="range" id="volume" min="0" max="1" step="0.05" value="0.8">
      </div>
      <button type="button" class="btn-cast" id="btnCast" data-cast-button title="Casta till Google Home / Chromecast">📺</button>

<button class="btn-wake" id="btnWake" title="Håll skärmen vaken">
        <svg class="icon-moon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M20 14.5A8.5 8.5 0 0 1 9.5 4 8.5 8.5 0 1 0 20 14.5Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
        </svg>
        <svg class="icon-sun" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="display:none">
          <circle cx="12" cy="12" r="4.5" stroke="currentColor" stroke-width="1.8"/>
          <path d="M12 2.5v2.2M12 19.3v2.2M21.5 12h-2.2M4.7 12H2.5M18.4 5.6l-1.55 1.55M7.15 16.85 5.6 18.4M18.4 18.4l-1.55-1.55M7.15 7.15 5.6 5.6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
        </svg>
      </button>
      <button class="btn-stop" id="btnStop" title="Stopp">⏹</button>
    </div>
  </div>
  <audio id="audioPlayer" preload="none"></audio>
</div>

<!-- Station Grid -->
<main class="main-content">
  <div class="station-grid" id="stationGrid">
    <?php foreach ($stations as $st): 
      $logoRel = '';
      if (!empty($st['logo'])) {
        $dbLogoRel = ltrim((string)$st['logo'], '/');
        if (is_file(__DIR__ . '/' . $dbLogoRel)) {
          $logoRel = $dbLogoRel;
        }
      }
      if ($logoRel === '') {
        $legacyLogo = 'assets/logos/' . $st['slug'] . '.png';
        if (is_file(__DIR__ . '/' . $legacyLogo)) {
          $logoRel = $legacyLogo;
        }
      }
      $hasLogo  = $logoRel !== '';
      $logoUrl  = $hasLogo ? $logoRel . '?v=' . filemtime(__DIR__ . '/' . $logoRel) : '';
      $initial  = mb_substr($st['name'], 0, 2, 'UTF-8');
      $online   = $st['is_online'] ?? 0;
      $metaText = trim(($st['meta_artist'] ? $st['meta_artist'] . ' – ' : '') . ($st['meta_title'] ?? ''));
      $stationStreams = $streamsByStation[(int)$st['id']] ?? [];
      $hasStreamSelect = $st['slug'] === 'p4-lokalt' && count($stationStreams) > 1;
    ?>
    <article class="station-card <?= $online ? 'online' : 'offline' ?>"
             data-id="<?= $st['id'] ?>"
             data-name="<?= htmlspecialchars($st['name']) ?>"
             data-base-name="<?= htmlspecialchars($st['name']) ?>"
             data-url="<?= htmlspecialchars(playbackUrl($st['stream_url'] ?? '', isset($st['stream_id']) ? (int)$st['stream_id'] : null)) ?>"
             data-stream-id="<?= isset($st['stream_id']) ? (int)$st['stream_id'] : '' ?>"
             data-meta="<?= htmlspecialchars($metaText) ?>"
             data-genre="<?= htmlspecialchars($st['genre'] ?? '') ?>"
             data-logo="<?= htmlspecialchars($logoUrl) ?>"
             data-initial="<?= htmlspecialchars($initial) ?>">
      <div class="card-logo">
        <?php if ($hasLogo): ?>
          <img src="<?= htmlspecialchars($logoUrl) ?>" alt="<?= htmlspecialchars($st['name']) ?>">
        <?php else: ?>
          <span class="logo-fallback"><?= htmlspecialchars($initial) ?></span>
        <?php endif; ?>
        <span class="status-dot <?= $online ? 'dot-green' : 'dot-red' ?>" title="<?= $online ? 'Online' : 'Offline' ?>"></span>
      </div>
      <div class="card-info">
        <h3><?= htmlspecialchars($st['name']) ?></h3>
        <?php if ($st['genre']): ?><span class="genre-tag"><?= htmlspecialchars($st['genre']) ?></span><?php endif; ?>
        <?php if ($hasStreamSelect): ?>
          <label class="stream-select-wrap" aria-label="Välj lokal P4-kanal">
            <span>P4-kanal</span>
            <select class="station-stream-select">
              <?php foreach ($stationStreams as $stream): ?>
              <?php $streamMetaText = trim(($stream['meta_artist'] ? $stream['meta_artist'] . ' – ' : '') . ($stream['meta_title'] ?? '')); ?>
              <option value="<?= htmlspecialchars(playbackUrl($stream['url'], isset($stream['id']) ? (int)$stream['id'] : null)) ?>" data-name="<?= htmlspecialchars($stream['label'] ?: $st['name']) ?>" data-stream-id="<?= (int)$stream['id'] ?>" data-meta="<?= htmlspecialchars($streamMetaText) ?>" <?= ($stream['url'] === $st['stream_url']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($stream['label'] ?: $st['name']) ?>
              </option>
              <?php endforeach; ?>
            </select>
          </label>
        <?php endif; ?>
        <p class="meta-text" id="meta-<?= $st['id'] ?>" <?= $metaText ? '' : 'hidden' ?>><?= htmlspecialchars($metaText) ?></p>
      </div>
      <button class="btn-card-play" title="Spela <?= htmlspecialchars($st['name']) ?>">▶</button>
    </article>
    <?php endforeach; ?>
  </div>
  <p class="no-results" id="noResults" style="display:none">Inga kanaler matchar.</p>
</main>

<footer class="site-footer">
  <a href="admin/">⚙️ Admin</a> &nbsp;·&nbsp;
  <?= count($stations) ?> kanaler
</footer>

<script src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1"></script>
<script src="assets/js/app.js?v=<?php echo filemtime(__DIR__ . '/assets/js/app.js'); ?>"></script>
</body>
</html>
