<?php
// /v6/share.php
// v2025-11-06h — FIX WA uniquement (og:url/canonical = /v6/). Facebook INCHANGÉ (carré + avant-titre).

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Vary: User-Agent');
header('X-Content-Type-Options: nosniff');

/* ---------- Utils ---------- */
function scheme(){ return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; }
function host(){ return $_SERVER['HTTP_HOST'] ?? 'localhost'; }
function base_dir_url(){
  $dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
  return scheme().'://'.host().$dir;
}
function current_url(){ return scheme().'://'.host().($_SERVER['REQUEST_URI'] ?? '/v6/share.php'); }
function site_root_url(){ return scheme().'://'.host().'/v6/'; }
function ensure_dir($p){ if(!is_dir($p)) @mkdir($p,0775,true); }
function is_url($u){ return (bool)preg_match('#^https?://#i',$u); }
function fs_to_url($fs){
  $rel = ltrim(str_replace(['\\', __DIR__], ['/', ''], $fs), '/');
  $u = base_dir_url().'/'.$rel;
  return (scheme()==='https') ? preg_replace('#^http:#','https:',$u) : $u;
}

/**
 * Télécharge + crop cover → JPEG *versionné dans le NOM* (pas de query)
 * Retourne [url, filemtime].
 */
function make_cover_versioned($src, $tw, $th){
  $dir = __DIR__.'/cache/covers'; ensure_dir($dir);
  $key = sha1($src)."_{$tw}x{$th}";
  $stable = "$dir/$key.jpg";

  if (!file_exists($stable) || (time()-filemtime($stable) > 3600)) {
    $tmp = "$dir/$key.src";
    $ctx = stream_context_create([
      'http'=>['timeout'=>8,'follow_location'=>1,'user_agent'=>'GSA-PlayerV6/1.0'],
      'ssl' =>['verify_peer'=>false,'verify_peer_name'=>false]
    ]);
    @file_put_contents($tmp, @file_get_contents($src,false,$ctx));
    if (@filesize($tmp)) {
      $img = @imagecreatefromstring(@file_get_contents($tmp));
      @unlink($tmp);
      if ($img){
        $sw=imagesx($img); $sh=imagesy($img);
        $dstR=$tw/$th; $srcR=$sw/$sh;
        if($srcR>$dstR){ $newH=$sh; $newW=(int)round($sh*$dstR); $sx=(int)(($sw-$newW)/2); $sy=0; }
        else{ $newW=$sw; $newH=(int)round($sw/$dstR); $sx=0; $sy=(int)(($sh-$newH)/2); }
        $cv=imagecreatetruecolor($tw,$th); imageinterlace($cv,true);
        imagecopyresampled($cv,$img,0,0,$sx,$sy,$tw,$th,$newW,$newH);
        imagejpeg($cv,$stable,82); imagedestroy($cv); imagedestroy($img);
      }
    } elseif (!file_exists($stable)) {
      return ['',0];
    }
  }

  $mtime = filemtime($stable);
  $ver   = "$dir/{$key}_v{$mtime}.jpg";
  if (!file_exists($ver)) {
    foreach (glob("$dir/{$key}_v*.jpg") as $old) @unlink($old);
    @copy($stable, $ver);
    @touch($ver, $mtime, $mtime);
  }
  return [ fs_to_url($ver), $mtime ];
}

/* ---------- Inputs ---------- */
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$platform = strtolower($_GET['platform'] ?? '');
if ($platform!=='fb' && $platform!=='wa') {
  if (preg_match('/facebookexternalhit|Facebot/i',$ua)) $platform='fb';
  elseif (preg_match('/WhatsApp/i',$ua)) $platform='wa';
  else $platform='wa'; // défaut WA (ne rien casser)
}

$titleRaw = trim($_GET['title'] ?? '');
$artist   = trim($_GET['artist'] ?? '');
$uParam   = trim($_GET['u'] ?? '');
$finalUrl = is_url($uParam) ? $uParam : site_root_url();

// FB: avant-titre paramétrable (optionnel)
$lead = strtolower(trim($_GET['lead'] ?? 'moment')); // 'moment' ou 'ecouter'
$leadText = ($lead==='ecouter') ? 'ÉCOUTER EN DIRECT : ' : 'EN CE MOMENT EN DIRECT : ';

/* Couverture : accepte cover/i/img/image/artwork/art ; urlenc/base64 */
$coverCandidates = [
  $_GET['cover'] ?? null, $_GET['i'] ?? null, $_GET['img'] ?? null,
  $_GET['image'] ?? null, $_GET['artwork'] ?? null, $_GET['art'] ?? null,
];
$coverSrc='';
foreach($coverCandidates as $c){
  if(!$c) continue;
  $try=$c;
  if(strpos($try,'%')!==false){ $d=urldecode($try); if(is_url($d)){ $coverSrc=$d; break; } }
  if(is_url($try)) { $coverSrc=$try; break; }
  $b=base64_decode($try,true);
  if($b!==false){
    $b2=(strpos($b,'%')!==false)?urldecode($b):$b;
    if(is_url($b2)){ $coverSrc=$b2; break; }
  }
}

/* Branding & textes */
$siteName='Global Streaming Africa';
$titleCore = ($titleRaw && $artist) ? "{$titleRaw} — {$artist}" : $siteName;
$titleFB   = $leadText.$titleCore; // FB: avant-titre
$titleWA   = ($titleRaw && $artist) ? "{$titleRaw} — {$artist} | {$siteName}" : "{$siteName} | Radio en direct";
$descWA    = "EN DIRECT sur {$siteName} — Écoute maintenant.";

/* Images */
$sqUrl=''; $sqTime=0; $rcUrl=''; $rcTime=0;
if ($coverSrc){
  list($sqUrl,$sqTime) = make_cover_versioned($coverSrc,1200,1200);
  list($rcUrl,$rcTime) = make_cover_versioned($coverSrc,1200,630);
}
$isFB = ($platform==='fb'); $isWA = !$isFB;

/* FB : image carrée unique (inchangé) */
if ($isFB) { $ogPrimary = $sqUrl ?: $rcUrl; }
/* WA : carré prioritaire */
if ($isWA) { $ogImage = $sqUrl ?: $rcUrl; $ogW = $sqUrl ? 1200 : 1200; $ogH = $sqUrl ? 1200 : 630; }

/* --- URLs déclarées dans les metas (WA ≠ FB) --- */
$selfBase = current_url();
if ($isWA) {
  // ✅ WhatsApp : URL courte/stable du player → preview immédiat (pas besoin d’ajouter “/”)
  $ogPageUrl = site_root_url();         // ex: https://v6.orifm.com/v6/
  $canonical = $ogPageUrl;
} else {
  // ✅ Facebook : COMPORTEMENT CONSERVÉ (self + clé version) → carré + avant-titre
  $verKey = substr(sha1(($sqTime ?: time()).$titleCore.microtime(true).mt_rand()), 0, 12);
  $ogPageUrl = $selfBase.(strpos($selfBase,'?')!==false ? '&' : '?').'v='.$verKey;
  $canonical = $ogPageUrl;
}

/* ---------- HTML ---------- */
?><!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<title><?= htmlspecialchars($isFB ? ($titleFB.' | '.$siteName) : $titleWA, ENT_QUOTES,'UTF-8') ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="canonical" href="<?= htmlspecialchars($canonical,ENT_QUOTES,'UTF-8') ?>" />

<!-- Open Graph -->
<meta property="og:type" content="website" />
<meta property="og:site_name" content="<?= htmlspecialchars($siteName,ENT_QUOTES,'UTF-8') ?>" />
<?php if($isFB): ?>
  <meta property="og:title" content="<?= htmlspecialchars($titleFB,ENT_QUOTES,'UTF-8') ?>" />
  <meta property="og:description" content="Écoute maintenant." />
<?php else: /* WA */ ?>
  <meta property="og:title" content="<?= htmlspecialchars($titleWA,ENT_QUOTES,'UTF-8') ?>" />
  <meta property="og:description" content="<?= htmlspecialchars($descWA,ENT_QUOTES,'UTF-8') ?>" />
<?php endif; ?>
<meta property="og:url" content="<?= htmlspecialchars($ogPageUrl,ENT_QUOTES,'UTF-8') ?>" />
<meta property="og:locale" content="fr_FR" />
<meta property="og:updated_time" content="<?= time() ?>" />
<?php if($isWA && !empty($ogImage)): ?>
  <meta property="og:image" content="<?= htmlspecialchars($ogImage,ENT_QUOTES,'UTF-8') ?>" />
  <meta property="og:image:secure_url" content="<?= htmlspecialchars(preg_replace('#^http:#','https:',$ogImage),ENT_QUOTES,'UTF-8') ?>" />
  <meta property="og:image:width" content="<?= $ogW ?>" />
  <meta property="og:image:height" content="<?= $ogH ?>" />
  <meta property="og:image:type" content="image/jpeg" />
  <meta property="og:image:alt" content="<?= htmlspecialchars($titleWA,ENT_QUOTES,'UTF-8') ?>" />
<?php elseif($isFB && !empty($ogPrimary)): ?>
  <meta property="og:image" content="<?= htmlspecialchars($ogPrimary,ENT_QUOTES,'UTF-8') ?>" />
  <meta property="og:image:secure_url" content="<?= htmlspecialchars(preg_replace('#^http:#','https:',$ogPrimary),ENT_QUOTES,'UTF-8') ?>" />
  <meta property="og:image:width" content="1200" />
  <meta property="og:image:height" content="1200" />
  <meta property="og:image:type" content="image/jpeg" />
  <meta property="og:image:alt" content="<?= htmlspecialchars($titleFB,ENT_QUOTES,'UTF-8') ?>" />
<?php endif; ?>

<!-- Twitter (optionnel) -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="<?= htmlspecialchars($isFB ? $titleFB : $titleWA,ENT_QUOTES,'UTF-8') ?>" />
<meta name="twitter:description" content="<?= htmlspecialchars($isFB ? 'Écoute maintenant.' : $descWA,ENT_QUOTES,'UTF-8') ?>" />
<?php $tw=$isWA?($ogImage??''):($ogPrimary??''); if(!empty($tw)): ?>
<meta name="twitter:image" content="<?= htmlspecialchars($tw,ENT_QUOTES,'UTF-8') ?>" />
<?php endif; ?>

<meta name="robots" content="noindex,nofollow" />
<style>
  html,body{margin:0;padding:0;background:#0b0b0b;color:#e8e8e8;font:16px/1.5 system-ui,Segoe UI,Roboto,Arial}
  .wrap{max-width:720px;margin:8vh auto;padding:24px}
  .badge{display:inline-block;padding:.25rem .5rem;border:1px solid #2ecc71;color:#2ecc71;border-radius:999px;font-size:.75rem;letter-spacing:.06em}
  h1{font-size:1.25rem;margin:.75rem 0 .25rem 0;font-weight:600}
  .muted{opacity:.8}
  .cover{width:100%;max-width:560px;aspect-ratio:1/1;object-fit:cover;border-radius:12px;display:block;margin:16px 0 8px 0}
  .back{display:inline-block;margin-top:12px;color:#9bdcff;text-decoration:none}
</style>
</head>
<body>
  <div class="wrap">
    <span class="badge">EN DIRECT</span>
    <h1><?= htmlspecialchars($isFB ? $titleFB : $titleWA, ENT_QUOTES,'UTF-8') ?></h1>
    <?php if($isWA && !empty($ogImage)): ?>
      <img class="cover" src="<?= htmlspecialchars($ogImage,ENT_QUOTES,'UTF-8') ?>" alt="<?= htmlspecialchars($titleWA,ENT_QUOTES,'UTF-8') ?>">
    <?php elseif($isFB && !empty($ogPrimary)): ?>
      <img class="cover" src="<?= htmlspecialchars($ogPrimary,ENT_QUOTES,'UTF-8') ?>" alt="<?= htmlspecialchars($titleFB,ENT_QUOTES,'UTF-8') ?>">
    <?php endif; ?>
    <a class="back" href="<?= htmlspecialchars($finalUrl,ENT_QUOTES,'UTF-8') ?>">← Ouvrir le player</a>
  </div>
</body>
</html>
