<?php
require __DIR__ . '/_auth.php';
requireLogin();

$db = db();
$id = intval($_GET['id'] ?? 0);

$station = $db->prepare("SELECT * FROM stations WHERE id=?")->execute([$id]) ?
           $db->query("SELECT * FROM stations WHERE id=$id")->fetch(PDO::FETCH_ASSOC) : null;

if (!$station) { flash('err', 'Kanalen hittades inte.'); header('Location: index.php'); exit; }

$streams = $db->query("SELECT * FROM streams WHERE station_id=$id ORDER BY priority")->fetchAll(PDO::FETCH_ASSOC);
$errors  = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name        = trim($_POST['name'] ?? '');
    $slug        = trim(preg_replace('/[^a-z0-9-]/', '-', strtolower($_POST['slug'] ?? '')), '-');
    $description = trim($_POST['description'] ?? '');
    $genre       = trim($_POST['genre'] ?? '');
    $website     = trim($_POST['website'] ?? '');
    $sort_order  = intval($_POST['sort_order'] ?? 10);
    $newStreams   = [];

    foreach (($_POST['streams'] ?? []) as $s) {
        $url = trim($s['url'] ?? '');
        if ($url) $newStreams[] = $s;
    }

    if (!$name)            $errors[] = 'Namn krävs';
    if (!$slug)            $errors[] = 'Slug krävs';
    if (empty($newStreams)) $errors[] = 'Minst en stream krävs';

    // Slug-kollision mot andra kanaler
    $other = $db->query("SELECT id FROM stations WHERE slug='$slug' AND id!=$id")->fetchColumn();
    if ($other) $errors[] = 'Slug är redan tagen av en annan kanal';

    if (!$errors) {
        $db->prepare("UPDATE stations SET name=?,slug=?,description=?,genre=?,website=?,sort_order=?,updated_at=CURRENT_TIMESTAMP WHERE id=?")
           ->execute([$name,$slug,$description,$genre,$website,$sort_order,$id]);

        // Ersätt streams
        $db->prepare("DELETE FROM streams WHERE station_id=?")->execute([$id]);
        foreach ($newStreams as $p => $s) {
            $db->prepare("INSERT INTO streams (station_id,url,format,bitrate,priority,label) VALUES (?,?,?,?,?,?)")
               ->execute([$id, trim($s['url']), $s['format']??'mp3', intval($s['bitrate']??128), $p+1, trim($s['label']??'Primär')]);
            $db->prepare("INSERT OR IGNORE INTO stream_status (stream_id,online) VALUES (?,0)")
               ->execute([$db->lastInsertId()]);
        }

        flash('ok', "\"$name\" uppdaterad!");
        header('Location: index.php'); exit;
    }

    // Behåll POST-data vid fel
    $station = array_merge($station, compact('name','slug','description','genre','website','sort_order'));
    $streams = $newStreams;
}

adminHeader('Redigera: ' . htmlspecialchars($station['name']));
?>
<?php if ($errors): ?>
<div class="alert alert-error"><?= implode('<br>', array_map('htmlspecialchars', $errors)) ?></div>
<?php endif; ?>

<div class="card-form">
<form method="post">
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
    <div class="form-group">
      <label>Namn *</label>
      <input name="name" class="form-control" value="<?= htmlspecialchars($station['name']) ?>" required>
    </div>
    <div class="form-group">
      <label>Slug *</label>
      <input name="slug" class="form-control" value="<?= htmlspecialchars($station['slug']) ?>">
    </div>
  </div>

  <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
    <div class="form-group">
      <label>Genre</label>
      <input name="genre" class="form-control" value="<?= htmlspecialchars($station['genre'] ?? '') ?>">
    </div>
    <div class="form-group">
      <label>Sorteringsordning</label>
      <input type="number" name="sort_order" class="form-control" value="<?= $station['sort_order'] ?>">
    </div>
  </div>

  <div class="form-group">
    <label>Beskrivning</label>
    <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($station['description'] ?? '') ?></textarea>
  </div>

  <div class="form-group">
    <label>Webbplats</label>
    <input name="website" class="form-control" value="<?= htmlspecialchars($station['website'] ?? '') ?>">
  </div>

  <div class="form-group">
    <label>Streams</label>
    <div id="streamList">
      <?php foreach ($streams as $i => $s): ?>
      <div class="stream-row">
        <input name="streams[<?=$i?>][url]"     class="form-control" value="<?= htmlspecialchars($s['url']) ?>" placeholder="https://…">
        <select name="streams[<?=$i?>][format]" class="form-control" style="max-width:90px">
          <?php foreach (['mp3','aac','ogg','hls'] as $f): ?>
          <option <?= ($s['format']??'mp3')===$f?'selected':'' ?>><?= $f ?></option>
          <?php endforeach; ?>
        </select>
        <input name="streams[<?=$i?>][bitrate]" class="form-control" type="number" value="<?= $s['bitrate']??128 ?>" style="max-width:80px">
        <input name="streams[<?=$i?>][label]"   class="form-control" value="<?= htmlspecialchars($s['label']??'') ?>" placeholder="Primär/Backup" style="max-width:110px">
        <button type="button" class="btn-rm" onclick="this.closest('.stream-row').remove()">✕</button>
      </div>
      <?php endforeach; ?>
    </div>
    <button type="button" id="addStreamBtn" class="btn btn-secondary" style="margin-top:8px">+ Lägg till stream</button>
    <p class="form-hint">Ordningen avgör prioritet – överst = primär. Backup provas automatiskt vid problem.</p>
  </div>

  <div style="display:flex;gap:12px;justify-content:flex-end;margin-top:8px">
    <a href="index.php" class="btn btn-secondary">Avbryt</a>
    <a href="delete.php?id=<?= $id ?>" class="btn btn-danger"
       onclick="return confirm('Ta bort <?= addslashes($station['name']) ?>?')">🗑 Ta bort</a>
    <button type="submit" class="btn btn-primary">💾 Spara</button>
  </div>
</form>
</div>

<script src="../assets/js/admin.js"></script>
<?php adminFooter(); ?>
