<?php
// /v6/api/lyrics.php
// API Paroles tolérante (lecture multi-sources)
// - GET  : ?artist=&title=  |  ?artist=&song=  |  ?key=artist|title
// - POST : JSON {artist, title, lyrics, key?} -> upsert (écrit dans /v6/data/lyrics.json)

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$PRIMARY_FILE = __DIR__ . '/../data/lyrics.json'; // destination d'écriture (POST)

// Emplacements possibles (lecture seulement) — ordre de priorité
$CANDIDATES = [
  $PRIMARY_FILE,
  dirname(__DIR__) . '/../admin-radio/data/lyrics.json',
  dirname(__DIR__) . '/../assets/data/lyrics.json',
  dirname(__DIR__) . '/../system/data/lyrics.json',
  dirname(__DIR__) . '/../data/lyrics.json', // fallback si déplacé
];

// ---------------- helpers ----------------
function tidy($s){ return trim((string)($s ?? '')); }

function deburr($s){
  $s = tidy($s);
  $s = @iconv('UTF-8','ASCII//TRANSLIT//IGNORE',$s);
  if ($s === false) $s = tidy($s);
  $s = preg_replace('/[^A-Za-z0-9\|\-\s_]/',' ', $s);
  $s = preg_replace('/\s+/',' ', $s);
  return strtolower(trim($s));
}
function key_of($artist,$title){ return deburr($artist).'|'.deburr($title); }

function load_json($file){
  if (!is_file($file)) return [];
  $raw = @file_get_contents($file);
  if ($raw === false || $raw === '') return [];
  $j = json_decode($raw, true);
  return is_array($j) ? $j : [];
}

function load_store_multi($files){
  $store = [];
  foreach ($files as $f){
    $arr = load_json($f);
    if (!$arr) continue;
    // Merge non destructif : le premier fichier dans la liste a la priorité
    foreach ($arr as $k => $row){
      if (!isset($store[$k])) $store[$k] = $row;
    }
  }
  return $store;
}

function save_store($file,$arr){
  @mkdir(dirname($file),0775,true);
  return (bool)@file_put_contents($file, json_encode($arr, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
}

// Charge toutes les sources disponibles (lecture)
$store = load_store_multi($CANDIDATES);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

// ---------- READ (GET) ----------
if ($method === 'GET') {
  $artist = $_GET['artist'] ?? '';
  $title  = $_GET['title']  ?? ($_GET['song'] ?? '');
  $key    = $_GET['key']    ?? '';

  // Index tolérant : clé normalisée -> entrée
  $normIndex = [];
  foreach ($store as $k => $row) {
    $normIndex[deburr($k)] = $row;
    // si artiste/titre présents, on indexe aussi
    $a = $row['artist'] ?? ''; $t = $row['title'] ?? '';
    if ($a !== '' && $t !== '') {
      $normIndex[key_of($a,$t)] = $row;
    }
  }

  $lyrics = '';
  if (tidy($artist) && tidy($title)) {
    $nk = key_of($artist, $title);
    if (isset($normIndex[$nk])) $lyrics = $normIndex[$nk]['lyrics'] ?? '';
  } elseif (tidy($key)) {
    $nk = deburr($key);
    if (isset($normIndex[$nk])) $lyrics = $normIndex[$nk]['lyrics'] ?? '';
  }

  if ($lyrics !== '') {
    echo json_encode(['ok'=>true,'lyrics'=>$lyrics], JSON_UNESCAPED_UNICODE);
  } else {
    http_response_code(404);
    echo json_encode(['ok'=>false,'lyrics'=>''], JSON_UNESCAPED_UNICODE);
  }
  exit;
}

// ---------- UPSERT (POST) ----------
if ($method === 'POST') {
  $raw = file_get_contents('php://input') ?: '';
  $in  = json_decode($raw,true);
  if (!is_array($in) || !$in) $in = $_POST;

  $artist = tidy($in['artist'] ?? '');
  $title  = tidy($in['title']  ?? '');
  $key    = tidy($in['key']    ?? '');
  $lyrics = tidy($in['lyrics'] ?? '');

  if ($key === '' && ($artist!=='' && $title!=='')) $key = key_of($artist,$title);
  if ($key === '') { http_response_code(400); echo json_encode(['ok'=>false,'message'=>'Clé invalide'], JSON_UNESCAPED_UNICODE); exit; }

  // Recharger le fichier primaire (écriture)
  $primary = load_json($PRIMARY_FILE);

  if (!isset($primary[$key])) {
    $primary[$key] = ['artist'=>$artist,'title'=>$title,'lyrics'=>$lyrics];
  } else {
    if ($artist!=='') $primary[$key]['artist'] = $artist;
    if ($title!=='')  $primary[$key]['title']  = $title;
    $primary[$key]['lyrics'] = $lyrics;
  }

  if (!save_store($PRIMARY_FILE,$primary)) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'message'=>'Échec d\'écriture'], JSON_UNESCAPED_UNICODE);
    exit;
  }

  echo json_encode(['ok'=>true,'message'=>'Paroles enregistrées','key'=>$key], JSON_UNESCAPED_UNICODE);
  exit;
}

// ---------- not allowed ----------
http_response_code(405);
echo json_encode(['ok'=>false,'message'=>'Méthode non autorisée'], JSON_UNESCAPED_UNICODE);
