<?php
// /admin-radio/index.php
require_once __DIR__ . '/../v6/admin-lib.php';
v6_guard();

session_start();
$flash_ok  = $_SESSION['v6_ok']  ?? null;
$flash_err = $_SESSION['v6_err'] ?? null;
unset($_SESSION['v6_ok'], $_SESSION['v6_err']);

$tab = $_GET['tab'] ?? 'settings';

// Actions POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if ($tab === 'settings') {
    if (isset($_POST['save_settings'])) {
      $cfg = v6_read_json('config.json', []);
      $cfg['station_name'] = trim($_POST['station_name'] ?? ($cfg['station_name'] ?? ''));
      $cfg['stream_url']   = trim($_POST['stream_url']   ?? ($cfg['stream_url']   ?? ''));
      $cfg['allowed_hosts']= array_filter(array_map('trim', explode("\n", $_POST['allowed_hosts'] ?? '')));
      $cfg['theme'] = [
        'background' => $_POST['theme_bg'] ?? '#111827',
        'text'       => $_POST['theme_text'] ?? '#ffffff',
      ];
      $cfg['ui'] = [
        'auto_play'         => isset($_POST['ui_auto_play']),
        'show_volume_bar'   => isset($_POST['ui_show_volume_bar']),
        'show_station_name' => isset($_POST['ui_show_station_name']),
        'show_slogan'       => isset($_POST['ui_show_slogan']),
      ];
      $cfg['legal'] = [
        'privacy_popup' => $_POST['privacy_popup'] ?? null,
        'terms_popup'   => $_POST['terms_popup']   ?? null,
      ];
      $cfg['cb'] = time();

      v6_write_json('config.json', $cfg);
      $_SESSION['v6_ok'] = 'Paramètres enregistrés.';
      header('Location: ?tab=settings'); exit;
    }
    if (isset($_POST['upload_cover'])) {
      $err = null;
      $url = v6_upload_cover($_FILES['cover'] ?? [], $err);
      if ($url) {
        $cfg = v6_read_json('config.json', []);
        $cfg['default_cover'] = $url;
        $cfg['cb'] = time();
        v6_write_json('config.json', $cfg);
        $_SESSION['v6_ok'] = 'Pochette par défaut mise à jour.';
      } else {
        $_SESSION['v6_err'] = $err ?: 'Upload impossible.';
      }
      header('Location: ?tab=settings'); exit;
    }
  }

  if ($tab === 'lyrics') {
    if (isset($_POST['add_lyrics'])) {
      $artist = trim($_POST['artist'] ?? '');
      $title  = trim($_POST['title'] ?? '');
      $text   = trim($_POST['text'] ?? '');

      if ($artist !== '' && $title !== '' && $text !== '') {
        $key = v6_lyrics_key($artist, $title);
        $db  = v6_read_json('lyrics.json', []);
        $db[$key] = $text;
        v6_write_json('lyrics.json', $db);
        $_SESSION['v6_ok'] = "Paroles enregistrées (clé: $key).";
      } else {
        $_SESSION['v6_err'] = 'Champs requis manquants.';
      }
      header('Location: ?tab=lyrics'); exit;
    }

    if (isset($_POST['save_text']) && isset($_POST['key'])) {
      $key = $_POST['key'];
      $db  = v6_read_json('lyrics.json', []);
      if (isset($db[$key])) {
        $db[$key] = trim($_POST['text'] ?? '');
        v6_write_json('lyrics.json', $db);
        $_SESSION['v6_ok'] = 'Paroles mises à jour.';
      }
      header('Location: ?tab=lyrics'); exit;
    }

    if (isset($_POST['delete_key'])) {
      $key = $_POST['delete_key'];
      $db  = v6_read_json('lyrics.json', []);
      if (isset($db[$key])) {
        unset($db[$key]);
        v6_write_json('lyrics.json', $db);
        $_SESSION['v6_ok'] = 'Entrée supprimée.';
      }
      header('Location: ?tab=lyrics'); exit;
    }

    if (isset($_POST['import_json'])) {
      if (!empty($_FILES['file']['tmp_name'])) {
        $raw = file_get_contents($_FILES['file']['tmp_name']);
        $json = json_decode($raw, true);
        if (is_array($json)) {
          $normalized = [];
          foreach ($json as $k => $v) {
            if (is_string($k)) {
              $normalized[$k] = (string)$v;
            } elseif (is_array($v) && isset($v['artist'],$v['title'],$v['text'])) {
              $nk = v6_lyrics_key($v['artist'], $v['title']);
              $normalized[$nk] = (string)$v['text'];
            }
          }
          $cur = v6_read_json('lyrics.json', []);
          $merged = array_merge($cur, $normalized);
          v6_write_json('lyrics.json', $merged);
          $_SESSION['v6_ok'] = 'Importation terminée.';
        } else {
          $_SESSION['v6_err'] = 'JSON invalide.';
        }
      }
      header('Location: ?tab=lyrics'); exit;
    }
  }
}

// export JSON
if ($tab === 'lyrics' && isset($_GET['export']) && $_GET['export']=='1') {
  $out = v6_read_json('lyrics.json', []);
  header('Content-Type: application/json; charset=UTF-8');
  header('Content-Disposition: attachment; filename="lyrics-export.json"');
  echo json_encode($out, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
  exit;
}

// Lecture données pour affichage
$config = v6_read_json('config.json', []);
$htmlFiles = v6_list_html_files();

$q = isset($_GET['q']) ? v6_normalize($_GET['q']) : '';
$lyrics = v6_read_json('lyrics.json', []);
ksort($lyrics);
if ($q) {
  $lyrics = array_filter($lyrics, function($text, $key) use ($q) {
    return (strpos($key, $q)!==false) || (strpos(v6_normalize($text), $q)!==false);
  }, ARRAY_FILTER_USE_BOTH);
}

// ——— HTML (utilise tes assets existants) ———
?><!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Radio Player V6 — Admin</title>
<link rel="stylesheet" href="/assets/css/main.css"><?php /* adapte si besoin */ ?>
<style>
  body{background:#f5f7fb;font-family:Inter,system-ui,Arial,sans-serif;}
  .wrap{max-width:1200px;margin:32px auto;padding:0 16px;}
  .tabs a{display:inline-block;padding:10px 14px;margin-right:6px;border-radius:8px;text-decoration:none;background:#e9edf7;color:#1f2937}
  .tabs a.active{background:#111827;color:#fff}
  .card{background:#fff;border-radius:14px;box-shadow:0 8px 20px rgba(17,24,39,.06);padding:18px}
  .grid{display:grid;gap:16px}
  .g2{grid-template-columns:1fr 1fr}
  label{font-weight:600;margin-top:8px;display:block}
  input[type=text], input[type=url], textarea, select {width:100%;padding:10px;border:1px solid #e5e7eb;border-radius:10px}
  .row{display:flex;gap:10px;align-items:center}
  .btn{display:inline-block;background:#1f4bff;color:#fff;border:none;padding:10px 14px;border-radius:10px;cursor:pointer}
  .btn.secondary{background:#6b7280}
  .btn.outline{background:#fff;color:#1f4bff;border:1px solid #1f4bff}
  .alert{padding:10px 14px;border-radius:8px;margin-bottom:14px}
  .success{background:#e8fbf0;color:#0f5132}
  .error{background:#fdecec;color:#7f1d1d}
  table{width:100%;border-collapse:collapse}
  th,td{border-bottom:1px solid #eef2f7;padding:10px;vertical-align:top}
  code{background:#f3f4f6;padding:2px 6px;border-radius:6px}
</style>
</head>
<body>
<div class="wrap">
  <h1 style="margin:0 0 10px 0">Radio Player V6 — Administration</h1>
  <div class="tabs" style="margin-bottom:16px">
    <a class="<?= $tab==='settings'?'active':'' ?>" href="?tab=settings">Paramètres</a>
    <a class="<?= $tab==='lyrics'?'active':'' ?>" href="?tab=lyrics">Paroles (Lyrics)</a>
  </div>

  <?php if($flash_ok): ?><div class="alert success"><?= htmlspecialchars($flash_ok) ?></div><?php endif; ?>
  <?php if($flash_err): ?><div class="alert error"><?= htmlspecialchars($flash_err) ?></div><?php endif; ?>

  <?php if($tab==='settings'): ?>
    <div class="grid g2">
      <div class="card">
        <form method="post">
          <input type="hidden" name="save_settings" value="1">
          <label>Nom de la station</label>
          <input type="text" name="station_name" value="<?= htmlspecialchars($config['station_name'] ?? '') ?>">

          <label>URL du flux</label>
          <input type="url" name="stream_url" value="<?= htmlspecialchars($config['stream_url'] ?? '') ?>">

          <div class="row">
            <div style="flex:1">
              <label>Thème — Fond (hex)</label>
              <input type="text" name="theme_bg" value="<?= htmlspecialchars($config['theme']['background'] ?? '#111827') ?>">
            </div>
            <div style="flex:1">
              <label>Thème — Texte (hex)</label>
              <input type="text" name="theme_text" value="<?= htmlspecialchars($config['theme']['text'] ?? '#ffffff') ?>">
            </div>
          </div>

          <label>Allowed hosts (un par ligne)</label>
          <textarea name="allowed_hosts" rows="3"><?= htmlspecialchars(implode("\n", $config['allowed_hosts'] ?? [])) ?></textarea>

          <div class="row" style="gap:18px;margin:10px 0">
            <label><input type="checkbox" name="ui_auto_play"        <?= !empty($config['ui']['auto_play'])?'checked':''; ?>> Auto-play</label>
            <label><input type="checkbox" name="ui_show_volume_bar"  <?= !empty($config['ui']['show_volume_bar'])?'checked':''; ?>> Barre volume</label>
            <label><input type="checkbox" name="ui_show_station_name"<?= !empty($config['ui']['show_station_name'] ?? true)?'checked':''; ?>> Nom station</label>
            <label><input type="checkbox" name="ui_show_slogan"      <?= !empty($config['ui']['show_slogan'])?'checked':''; ?>> Slogan</label>
          </div>

          <div class="row">
            <div style="flex:1">
              <label>Privacy (popup)</label>
              <select name="privacy_popup">
                <option value="">—</option>
                <?php foreach($htmlFiles as $f): ?>
                  <option value="<?= $f ?>" <?= ( ($config['legal']['privacy_popup'] ?? null) === $f ? 'selected':'' ) ?>><?= basename($f) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div style="flex:1">
              <label>Terms (popup)</label>
              <select name="terms_popup">
                <option value="">—</option>
                <?php foreach($htmlFiles as $f): ?>
                  <option value="<?= $f ?>" <?= ( ($config['legal']['terms_popup'] ?? null) === $f ? 'selected':'' ) ?>><?= basename($f) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

          <div style="margin-top:12px">
            <button class="btn">Enregistrer</button>
            <span style="margin-left:8px;color:#6b7280;font-size:12px">Cache-buster mis à jour automatiquement.</span>
          </div>
        </form>
      </div>

      <div class="card">
        <h3 style="margin-top:0">Pochette par défaut</h3>
        <img src="<?= htmlspecialchars(($config['default_cover'] ?? '/v6/img/cover.jpeg') . '?cb=' . ($config['cb'] ?? time())) ?>"
             style="max-width:100%;height:auto;border-radius:12px;box-shadow:0 4px 12px rgba(0,0,0,.08);margin-bottom:10px">
        <form method="post" enctype="multipart/form-data">
          <input type="hidden" name="upload_cover" value="1">
          <input type="file" name="cover" accept=".jpg,.jpeg,.png,.webp">
          <div style="margin-top:8px"><button class="btn outline">Téléverser (≤ 2 Mo)</button></div>
        </form>
      </div>
    </div>
  <?php endif; ?>

  <?php if($tab==='lyrics'): ?>
    <div class="grid g2">
      <div class="card">
        <h3 style="margin-top:0">Ajouter / Mettre à jour</h3>
        <form method="post">
          <input type="hidden" name="add_lyrics" value="1">
          <label>Artiste</label>
          <input type="text" name="artist" placeholder="ex: Des’ree" required>
          <label>Titre</label>
          <input type="text" name="title" placeholder="ex: You Gotta Be" required>
          <label>Paroles</label>
          <textarea name="text" rows="8" placeholder="Collez les paroles…" required></textarea>
          <div style="margin-top:10px"><button class="btn">Enregistrer</button></div>
          <p style="color:#6b7280;font-size:12px;margin-top:8px">Normalisation & alias appliqués (clé = artiste|titre, sans accents).</p>
        </form>

        <hr style="margin:18px 0;border:0;border-top:1px solid #eef2f7">

        <h3>Import / Export</h3>
        <div class="row">
          <a class="btn outline" href="?tab=lyrics&export=1">Exporter JSON</a>
          <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="import_json" value="1">
            <input type="file" name="file" accept=".json,application/json,text/plain" required>
            <button class="btn secondary">Importer</button>
          </form>
        </div>
      </div>

      <div class="card">
        <form method="get" class="row" style="margin-bottom:10px">
          <input type="hidden" name="tab" value="lyrics">
          <input type="text" name="q" value="<?= htmlspecialchars($_GET['q'] ?? '') ?>" placeholder="Rechercher (clé ou texte)…" style="flex:1">
          <button class="btn secondary">Chercher</button>
        </form>

        <div style="max-height:70vh;overflow:auto">
          <table>
            <thead><tr><th>Clé</th><th>Paroles</th><th style="width:120px">Actions</th></tr></thead>
            <tbody>
            <?php if(empty($lyrics)): ?>
              <tr><td colspan="3" style="text-align:center;color:#6b7280">Aucune entrée</td></tr>
            <?php else: foreach($lyrics as $key => $text): ?>
              <tr>
                <td><code><?= htmlspecialchars($key) ?></code></td>
                <td>
                  <form method="post">
                    <input type="hidden" name="save_text" value="1">
                    <input type="hidden" name="key" value="<?= htmlspecialchars($key) ?>">
                    <textarea name="text" rows="5"><?= htmlspecialchars($text) ?></textarea>
                    <div style="margin-top:8px">
                      <button class="btn btn-sm">Sauvegarder</button>
                    </div>
                  </form>
                </td>
                <td>
                  <form method="post" onsubmit="return confirm('Supprimer cette entrée ?');">
                    <input type="hidden" name="delete_key" value="<?= htmlspecialchars($key) ?>">
                    <button class="btn secondary">Supprimer</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>

      </div>
    </div>
  <?php endif; ?>

</div>
</body>
</html>
