<?php
/**
 * Radio Player V6 — Admin (Paramètres, Paroles, Pages légales)
 * Ecrit/Lit dans /v6/data/* et /v6/img/* — pas de changement des endpoints publics.
 */

session_start();

/* ================= Helpers fichiers & normalisation ================= */
function v6_base() { return __DIR__ . '/../v6/'; }
function v6_data() { return v6_base() . 'data/'; }
function v6_img()  { return v6_base() . 'img/'; }

function v6_read_json($file, $default = []) {
  $path = v6_data() . $file;
  if (!is_file($path)) return $default;
  $raw = file_get_contents($path);
  $json = json_decode($raw, true);
  return is_array($json) ? $json : $default;
}
function v6_write_json($file, array $data) {
  @mkdir(v6_data(), 0775, true);
  $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
  return (bool) file_put_contents(v6_data().$file, json_encode($data, $flags));
}
function v6_read_html($file){ $p = v6_data().$file; return is_file($p) ? file_get_contents($p) : ''; }
function v6_write_html($file,$html){ @mkdir(v6_data(),0775,true); return (bool)file_put_contents(v6_data().$file,$html); }

function v6_normalize($s) {
  $s = trim(mb_strtolower($s,'UTF-8'));
  $s = preg_replace('/\s+/', ' ', $s);
  $s = str_replace(["’","'","`","´"], '', $s);
  $s = iconv('UTF-8','ASCII//TRANSLIT//IGNORE',$s);
  $s = preg_replace('/[^a-z0-9 \|\-]/','',$s);
  return trim($s);
}
function v6_aliases(){ static $a; if($a===null){ $a = v6_read_json('aliases.json', []);} return $a; }
function v6_alias_of($artist){ $n=v6_normalize($artist); $a=v6_aliases(); return $a[$n] ?? $n; }
function v6_lyrics_key($artist,$title){ return v6_normalize(v6_alias_of($artist)).'|'.v6_normalize($title); }

function v6_list_html_files(){
  $g = glob(v6_data().'*.html') ?: [];
  return array_map(fn($p)=>'/v6/data/'.basename($p), $g);
}

/** Upload cover → toujours /v6/img/cover.jpg (JPEG via GD) */
function v6_upload_cover_to_jpg($file,&$err=null){
  if(empty($file['tmp_name'])){ $err='Aucun fichier.'; return null; }
  if($file['error']!==UPLOAD_ERR_OK){ $err='Erreur d’upload.'; return null; }
  if($file['size']>2*1024*1024){ $err='Fichier > 2 Mo.'; return null; }

  $finfo=finfo_open(FILEINFO_MIME_TYPE);
  $mime=finfo_file($finfo,$file['tmp_name']);
  finfo_close($finfo);

  $allowed=['image/jpeg','image/png','image/webp'];
  if(!in_array($mime,$allowed,true)){ $err='Type non autorisé (jpg/png/webp).'; return null; }

  if($mime==='image/png'){
    $src=imagecreatefrompng($file['tmp_name']); imagepalettetotruecolor($src);
  } elseif($mime==='image/webp'){
    if(!function_exists('imagecreatefromwebp')){ $err='WEBP non supporté sur ce serveur.'; return null; }
    $src=imagecreatefromwebp($file['tmp_name']);
  } else {
    $src=imagecreatefromjpeg($file['tmp_name']);
  }
  if(!$src){ $err='Impossible de lire l’image.'; return null; }

  @mkdir(v6_img(),0775,true);
  $destPath=v6_img().'cover.jpg';
  $ok=imagejpeg($src, $destPath, 88);
  imagedestroy($src);
  if(!$ok){ $err='Ecriture cover.jpg impossible.'; return null; }

  return '/v6/img/cover.jpg';
}

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

/* ================= Onglets & redirections ================= */
$tab = $_GET['tab'] ?? 'settings';   // settings | lyrics | legal
$baseUrl = siteUrl . 'radio';
$go = function($t) use ($baseUrl){
  header('Location: '.$baseUrl.'?tab='.$t);
  exit;
};

/* ================= POST Actions ================= */
if($_SERVER['REQUEST_METHOD']==='POST'){

  // ------- Paramètres -------
  if($tab==='settings'){

    // Enregistrer paramètres
    if(isset($_POST['save_settings'])){
      $cfg = v6_read_json('config.json', []);
      $cfg['version']       = $cfg['version'] ?? '6.0.0';
      $cfg['station_name']  = trim($_POST['station_name'] ?? ($cfg['station_name'] ?? ''));
      $cfg['stream_url']    = trim($_POST['stream_url']   ?? ($cfg['stream_url']   ?? ''));
      if (!isset($cfg['platform'])) { $cfg['platform'] = 'shoutcast'; }

      $hosts = array_filter(array_map('trim', explode("\n", $_POST['allowed_hosts'] ?? '')));
      $cfg['allowed_hosts'] = array_values(array_unique($hosts));

      $cfg['theme'] = [
        'background' => $_POST['theme_bg']   ?? ($cfg['theme']['background'] ?? '#111827'),
        'text'       => $_POST['theme_text'] ?? ($cfg['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']),
      ];
      if (!isset($cfg['socials'])) { $cfg['socials'] = ['facebook'=>'','x'=>'','tiktok'=>'','instagram'=>'']; }
      $cfg['legal'] = [
        'privacy_popup' => $_POST['privacy_popup'] ?? ($cfg['legal']['privacy_popup'] ?? ''),
        'terms_popup'   => $_POST['terms_popup']   ?? ($cfg['legal']['terms_popup']   ?? ''),
      ];

      $cfg['cb'] = time(); // force refresh
      v6_write_json('config.json', $cfg);
      $_SESSION['v6_ok'] = 'Paramètres enregistrés.';
      $go('settings');
    }

    // Téléverser cover → converti en cover.jpg + met à jour config
    if(isset($_POST['upload_cover'])){
      $err=null; 
      $url=v6_upload_cover_to_jpg($_FILES['cover'] ?? [], $err);
      if($url){
        $cfg=v6_read_json('config.json',[]);
        $cfg['default_cover']='/v6/img/cover.jpg';
        $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.';
      }
      $go('settings');
    }

    // Vider cache (juste cb++)
    if(isset($_POST['clear_cache'])){
      $cfg=v6_read_json('config.json',[]);
      $cfg['cb']=time();
      v6_write_json('config.json',$cfg);
      $_SESSION['v6_ok']='Cache vidé (cb mis à jour).';
      $go('settings');
    }
  }

  // ------- Lyrics -------
  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.';
      }
      $go('lyrics');
    }
    if(isset($_POST['save_text'], $_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.';
      }
      $go('lyrics');
    }
    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.';
      }
      $go('lyrics');
    }
    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.';
        }
      }
      $go('lyrics');
    }
  }

  // ------- Pages légales -------
  if($tab==='legal' && isset($_POST['save_legal'])){
    $privacy = $_POST['privacy_html'] ?? '';
    $terms   = $_POST['terms_html']   ?? '';
    v6_write_html('privacy.html', $privacy);
    v6_write_html('terms.html',   $terms);

    $cfg = v6_read_json('config.json', []);
    if(empty($cfg['legal']['privacy_popup'])) $cfg['legal']['privacy_popup'] = '/v6/data/privacy.html';
    if(empty($cfg['legal']['terms_popup']))   $cfg['legal']['terms_popup']   = '/v6/data/terms.html';
    $cfg['cb'] = time();
    v6_write_json('config.json', $cfg);

    $_SESSION['v6_ok'] = 'Pages légales enregistrées.';
    $go('legal');
  }
}

/* ================= Données pour affichage ================= */
$config    = v6_read_json('config.json', []);
$htmlFiles = v6_list_html_files();
$privacyHtml = v6_read_html('privacy.html');
$termsHtml   = v6_read_html('terms.html');

$q = isset($_GET['qk']) ? v6_normalize($_GET['qk']) : '';
$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);
}

/* ================= Vue ================= */
?>
<div class="main-content">
  <section class="section">
    <ul class="breadcrumb breadcrumb-style ">
      <li class="breadcrumb-item"><h4 class="page-title m-b-0">Radio Player</h4></li>
      <li class="breadcrumb-item"><a href="<?=siteUrl?>"><i data-feather="home"></i></a></li>
      <li class="breadcrumb-item active"><?= $tab==='lyrics'?'Paroles (Lyrics)':($tab==='legal'?'Pages légales':'Paramètres') ?></li>
    </ul>

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

    <div class="card">
      <div class="card-body">
        <div class="buttons">
          <a href="<?=siteUrl?>radio?tab=settings" class="btn <?= $tab==='settings'?'btn-primary':'btn-outline-primary'?>">Paramètres</a>
          <a href="<?=siteUrl?>radio?tab=lyrics"   class="btn <?= $tab==='lyrics'  ?'btn-primary':'btn-outline-primary'?>">Paroles (Lyrics)</a>
          <a href="<?=siteUrl?>radio?tab=legal"    class="btn <?= $tab==='legal'   ?'btn-primary':'btn-outline-primary'?>">Pages légales</a>
        </div>
      </div>
    </div>

    <?php if($tab==='settings'): ?>
      <div class="row">
        <div class="col-lg-8">
          <div class="card">
            <div class="card-header"><h4>Paramètres du Player</h4></div>
            <div class="card-body">
              <form method="post">
                <input type="hidden" name="save_settings" value="1">

                <div class="row">
                  <div class="form-group col-md-6">
                    <label>Nom de la station</label>
                    <input type="text" class="form-control" name="station_name" value="<?= htmlspecialchars($config['station_name'] ?? '') ?>">
                  </div>
                  <div class="form-group col-md-6">
                    <label>URL du flux</label>
                    <input type="url" class="form-control" name="stream_url" placeholder="ex: https://studio.simbacast.com:1300/stream?sid=1" value="<?= htmlspecialchars($config['stream_url'] ?? '') ?>">
                  </div>
                </div>

                <div class="row">
                  <div class="form-group col-md-6">
                    <label>Couleur de fond (hex)</label>
                    <input type="text" class="form-control" name="theme_bg" value="<?= htmlspecialchars($config['theme']['background'] ?? '#111827') ?>">
                  </div>
                  <div class="form-group col-md-6">
                    <label>Couleur du texte (hex)</label>
                    <input type="text" class="form-control" name="theme_text" value="<?= htmlspecialchars($config['theme']['text'] ?? '#ffffff') ?>">
                  </div>
                </div>

                <div class="form-group">
                  <label>Domaines autorisés (un par ligne)</label>
                  <textarea class="form-control" name="allowed_hosts" rows="3" placeholder="studio.webradio.solutions&#10;studio.simbacast.com"><?= htmlspecialchars(implode("\n", $config['allowed_hosts'] ?? [])) ?></textarea>
                </div>

                <div class="form-group">
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="ui1" name="ui_auto_play" <?= !empty($config['ui']['auto_play'])?'checked':''; ?>>
                    <label class="custom-control-label" for="ui1">Auto-play</label>
                  </div>
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="ui2" name="ui_show_volume_bar" <?= !empty($config['ui']['show_volume_bar'])?'checked':''; ?>>
                    <label class="custom-control-label" for="ui2">Afficher la barre de volume</label>
                  </div>
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="ui3" name="ui_show_station_name" <?= !empty($config['ui']['show_station_name'] ?? true)?'checked':''; ?>>
                    <label class="custom-control-label" for="ui3">Afficher le nom de la station</label>
                  </div>
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="ui4" name="ui_show_slogan" <?= !empty($config['ui']['show_slogan'])?'checked':''; ?>>
                    <label class="custom-control-label" for="ui4">Afficher le slogan</label>
                  </div>
                </div>

                <div class="row">
                  <div class="form-group col-md-6">
                    <label>Privacy (popup)</label>
                    <select class="form-control" 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 class="form-group col-md-6">
                    <label>Terms (popup)</label>
                    <select class="form-control" 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 class="d-flex align-items-center">
                  <button class="btn btn-primary">Enregistrer</button>
                  <form method="post" class="ml-2">
                    <input type="hidden" name="clear_cache" value="1">
                    <button class="btn btn-outline-secondary">Vider le cache</button>
                  </form>
                  <span class="text-muted ml-3" style="font-size:12px">Le cache-buster (cb) est mis à jour automatiquement.</span>
                </div>
              </form>
            </div>
          </div>
        </div>

        <div class="col-lg-4">
          <div class="card">
            <div class="card-header"><h4>Pochette par défaut</h4></div>
            <div class="card-body">
              <img src="<?= htmlspecialchars(('/v6/img/cover.jpg').'?cb='.($config['cb'] ?? time())) ?>" style="max-width:100%;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" class="form-control">
                <button class="btn btn-outline-primary mt-2">Téléverser (≤ 2 Mo)</button>
              </form>
              <small class="text-muted d-block mt-2">Le fichier est normalisé vers <code>/v6/img/cover.jpg</code>.</small>
            </div>
          </div>
        </div>
      </div>
    <?php endif; ?>

    <?php if($tab==='lyrics'): ?>
      <div class="row">
        <div class="col-lg-4">
          <div class="card">
            <div class="card-header"><h4>Ajouter / Mettre à jour</h4></div>
            <div class="card-body">
              <form method="post">
                <input type="hidden" name="add_lyrics" value="1">
                <div class="form-group"><label>Artiste</label><input class="form-control" name="artist" placeholder="ex: Des’ree" required></div>
                <div class="form-group"><label>Titre</label><input class="form-control" name="title" placeholder="ex: You Gotta Be" required></div>
                <div class="form-group"><label>Paroles</label><textarea class="form-control" name="text" rows="8" placeholder="Collez les paroles…" required></textarea></div>
                <button class="btn btn-primary btn-block">Enregistrer</button>
                <p class="text-muted mt-2" style="font-size:12px">Normalisation & alias (clé = artiste|titre).</p>
              </form>
              <hr>
              <h6>Import / Export</h6>
              <div class="d-flex align-items-center">
                <a class="btn btn-outline-primary mr-2" href="<?=siteUrl?>radio?tab=lyrics&export=1">Exporter JSON</a>
                <form method="post" enctype="multipart/form-data" class="d-flex">
                  <input type="hidden" name="import_json" value="1">
                  <input type="file" name="file" accept=".json,application/json,text/plain" required class="form-control">
                  <button class="btn btn-secondary ml-2">Importer</button>
                </form>
              </div>
            </div>
          </div>
        </div>

        <div class="col-lg-8">
          <div class="card">
            <div class="card-header"><h4>Paroles (<?= count($lyrics) ?>)</h4></div>
            <div class="card-body">
              <form class="form-inline mb-3" method="get">
                <input type="hidden" name="tab" value="lyrics">
                <input class="form-control mr-2" name="qk" value="<?= htmlspecialchars($_GET['qk'] ?? '') ?>" placeholder="Rechercher (clé ou texte)…" style="flex:1">
                <button class="btn btn-secondary">Chercher</button>
              </form>
              <div style="max-height:65vh;overflow:auto">
                <table class="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" class="text-center text-muted">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 class="form-control" name="text" rows="5"><?= htmlspecialchars($text) ?></textarea>
                          <button class="btn btn-primary btn-sm mt-2">Sauvegarder</button>
                        </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 btn-danger btn-sm">Supprimer</button>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; endif; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    <?php endif; ?>

    <?php if($tab==='legal'): ?>
      <div class="row">
        <div class="col-lg-12">
          <div class="card">
            <div class="card-header"><h4>Pages légales</h4></div>
            <div class="card-body">
              <form method="post">
                <input type="hidden" name="save_legal" value="1">

                <div class="form-group">
                  <label>Privacy Policy (popup)</label>
                  <textarea class="form-control" name="privacy_html" rows="12" placeholder="HTML autorisé…"><?= htmlspecialchars($privacyHtml) ?></textarea>
                  <small class="text-muted">Enregistré dans <code>/v6/data/privacy.html</code>.</small>
                </div>

                <div class="form-group mt-4">
                  <label>Terms of Use (popup)</label>
                  <textarea class="form-control" name="terms_html" rows="12" placeholder="HTML autorisé…"><?= htmlspecialchars($termsHtml) ?></textarea>
                  <small class="text-muted">Enregistré dans <code>/v6/data/terms.html</code>.</small>
                </div>

                <button class="btn btn-primary mt-3">Enregistrer</button>
                <span class="text-muted ml-2" style="font-size:12px">Le cache-buster est mis à jour automatiquement.</span>
              </form>
            </div>
          </div>
        </div>
      </div>
    <?php endif; ?>

  </section>
</div>
