<?php
// /v6/admin-lib.php
// Helpers génériques pour le module Radio Player V6 (backend PHP pur).

if (!function_exists('v6_base')) {
  function v6_base() { return __DIR__ . '/'; }
  function v6_data() { return v6_base() . 'data/'; }
  function v6_img()  { return v6_base() . 'img/'; }

  function v6_read_json(string $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(string $file, array $data): bool {
    $path = v6_data() . $file;
    @mkdir(dirname($path), 0775, true);
    return (bool) file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
  }

  function v6_normalize(string $s): string {
    $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(): array {
    return v6_read_json('aliases.json', []);
  }

  function v6_alias_of(string $artist): string {
    $a = v6_normalize($artist);
    $aliases = v6_aliases();
    return $aliases[$a] ?? $a;
  }

  function v6_lyrics_key(string $artist, string $title): string {
    return v6_normalize(v6_alias_of($artist)) . '|' . v6_normalize($title);
  }

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

  function v6_upload_cover(array $file, &$error = null): ?string {
    if (empty($file['tmp_name'])) { $error = 'Aucun fichier.'; return null; }
    if ($file['error'] !== UPLOAD_ERR_OK) { $error = 'Erreur d’upload.'; return null; }
    if ($file['size'] > 2*1024*1024) { $error = 'Fichier > 2 Mo.'; return null; }

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

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

    $ext = $allowed[$mime];
    @mkdir(v6_img(), 0775, true);
    $name = "cover.$ext";
    $dest = v6_img() . $name;
    if (!move_uploaded_file($file['tmp_name'], $dest)) { $error = 'Move failed.'; return null; }

    return "/v6/img/$name";
  }

  function v6_guard() {
    // Hook d’auth très basique : on essaye d’inclure un init si tu en as un.
    $paths = [__DIR__.'/../core/init.php', __DIR__.'/../system/init.php'];
    foreach ($paths as $p) { if (is_file($p)) { require_once $p; break; } }
    // Si ton backend a déjà une vérif de session/role, elle s’appliquera ici via init.php.
  }
}
