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

$db = db();
$errors = [];
$vals   = ['name'=>'','slug'=>'','description'=>'','genre'=>'','website'=>'','sort_order'=>10,'streams'=>[['url'=>'','format'=>'mp3','bitrate'=>128,'priority'=>1,'label'=>'Primär']]];

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

    foreach (($_POST['streams'] ?? []) as $s) {
        $url = trim($s['url'] ?? '');
        if ($url) {
            $vals['streams'][] = [
                'url'      => $url,
                'format'   => $s['format'] ?? 'mp3',
                'bitrate'  => intval($s['bitrate'] ?? 128),
                'priority' => intval($s['priority'] ?? 1),
                'label'    => trim($s['label'] ?? 'Primär'),
            ];
        }
    }

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

    // Kontrollera unik slug
    $exists = $db->prepare("SELECT id FROM stations WHERE slug=?")->execute([$vals['slug']]);
    if ($db->prepare("SELECT id FROM stations WHERE slug=?")->execute([$vals['slug']]) && 
        $db->query("SELECT id FROM stations WHERE slug='{$vals['slug']}'")->fetchColumn()) {
        $errors[] = 'Slug är redan tagen';
    }

    if (!$errors) {
        $db->prepare("INSERT INTO stations (name,slug,description,genre,website,sort_order) VALUES (?,?,?,?,?,?)")
           ->execute([$vals['name'],$vals['slug'],$vals['description'],$vals['genre'],$vals['website'],$vals['sort_order']]);
        $sid = $db->lastInsertId();

        foreach ($vals['streams'] as $p => $s) {
            $db->prepare("INSERT INTO streams (station_id,url,format,bitrate,priority,label) VALUES (?,?,?,?,?,?)")
               ->execute([$sid,$s['url'],$s['format'],$s['bitrate'],$s['priority'],$s['label']]);
            $db->prepare("INSERT OR IGNORE INTO stream_status (stream_id,online) VALUES (?,0)")
               ->execute([$db->lastInsertId()]);
        }
        $db->prepare("INSERT OR IGNORE INTO metadata (station_id) VALUES (?)")->execute([$sid]);

        flash('ok', "Kanalen \"{$vals['name']}\" skapad!");
        header('Location: index.php'); exit;
    }
}

adminHeader('Ny kanal');
?>
<?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($vals['name']) ?>" required>
    </div>
    <div class="form-group">
      <label>Slug * <small>(URL-vänlig, unik)</small></label>
      <input name="slug" class="form-control" value="<?= htmlspecialchars($vals['slug']) ?>" placeholder="p1, rix-fm …">
    </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($vals['genre']) ?>" placeholder="Pop, Nyheter …">
    </div>
    <div class="form-group">
      <label>Sorteringsordning</label>
      <input type="number" name="sort_order" class="form-control" value="<?= $vals['sort_order'] ?>">
    </div>
  </div>

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

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

  <!-- Streams -->
  <div class="form-group">
    <label>Streams (flera = automatisk failover)</label>
    <div id="streamList">
      <?php foreach ($vals['streams'] as $i => $s): ?>
      <div class="stream-row">
        <input name="streams[<?=$i?>][url]"     class="form-control" placeholder="https://stream.example.com/…" value="<?= htmlspecialchars($s['url']) ?>">
        <select name="streams[<?=$i?>][format]" class="form-control" style="max-width:90px">
          <?php foreach (['mp3','aac','ogg','hls'] as $f): ?>
          <option <?= $s['format']===$f?'selected':'' ?>><?= $f ?></option>
          <?php endforeach; ?>
        </select>
        <input name="streams[<?=$i?>][bitrate]"  class="form-control" type="number" placeholder="kbps" value="<?= $s['bitrate'] ?>" style="max-width:80px">
        <input name="streams[<?=$i?>][label]"    class="form-control" placeholder="Primär/Backup" value="<?= htmlspecialchars($s['label']) ?>" style="max-width:110px">
        <input name="streams[<?=$i?>][priority]" type="hidden" class="priority-input" value="<?= $s['priority'] ?>">
        <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">Prioritet 1 = primär. Backup provas automatiskt om primär är nere.</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>
    <button type="submit" class="btn btn-primary">💾 Spara kanal</button>
  </div>
</form>
</div>

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