<?php
// =============================
// Voice Isolator — Success / Download (PHP)
// • Hidden debug
// • Clear wait message + spinner
// • Polls n8n exchange webhook for download link using session_id
// • "Clean more files" button back to voice-isolator.php
// =============================

$N8N_HOST   = "https://n8n.1522irondome.synology.me";       // your n8n host
$EXCHG_PATH = "/webhook/exchange-session";                  // <-- set to your real exchange webhook path
$nonce      = base64_encode(random_bytes(16));

// --- Security headers ---
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: strict-origin-when-cross-origin");
header("X-Frame-Options: DENY");
header("Permissions-Policy: interest-cohort=()");
header("Content-Security-Policy: default-src 'self'; img-src 'self' data: https://podcastpontifications.com; style-src 'self' 'unsafe-inline'; script-src 'self' 'nonce-$nonce'; connect-src 'self' $N8N_HOST; frame-ancestors 'none'; base-uri 'none'");

$sessionId = isset($_GET['session_id']) ? htmlspecialchars($_GET['session_id'], ENT_QUOTES) : '';
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Voice Isolator — Download</title>
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <meta name="color-scheme" content="dark light">
  <style>
    :root { --bg:#0b1022; --card:#111827; --muted:#9aa4b2; --text:#e5e7eb; --accent:#60a5fa; --ok:#34d399; --err:#f87171; --border:rgba(148,163,184,.25); color-scheme: dark; }
    html,body { height:100% }
    body{margin:0;font:16px/1.45 system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial;background:linear-gradient(180deg,#0b1022,#0e132b);color:var(--text);display:grid;place-items:center;min-height:100vh}
    .card{max-width:760px;width:clamp(340px,92vw,760px);background:rgba(17,24,39,.92);border:1px solid var(--border);border-radius:18px;padding:28px;box-shadow:0 14px 36px rgba(0,0,0,.35)}
    .header{ text-align:center; margin-bottom:10px; }
    .logo-img{ width:96px; height:auto; border-radius:10px; display:block; margin:0 auto 10px; }
    h1{margin:0 0 6px 0;font-size:22px;text-align:center}
    p.muted{color:var(--muted);text-align:center;margin:.25rem 0 1rem}

    .row{display:flex;gap:10px;flex-wrap:wrap;align-items:center;justify-content:center;margin-top:12px}
    .btn{padding:12px 16px;border-radius:12px;border:1px solid var(--border);background:linear-gradient(180deg,#2563eb,#1d4ed8);color:#fff;cursor:pointer;font-weight:600}
    .btn[disabled]{opacity:.65;cursor:not-allowed}
    .btn.secondary{background:#0f172a;color:#e5e7eb}
    .btn.ghost{background:transparent;color:#e5e7eb}

    .status{margin-top:12px;padding:12px;border-radius:12px;border:1px solid var(--border);background:rgba(59,130,246,.08);color:#c7d2fe;text-align:center}
    .status.err{background:rgba(248,113,113,.1);color:#fecaca;border-color:#f8717140}
    .status.ok{background:rgba(52,211,153,.1);color:#bbf7d0;border-color:#34d39933}

    /* Spinner */
    .spinner{width:40px;height:40px;border:3px solid rgba(96,165,250,.25);border-top-color:#60a5fa;border-radius:999px;animation:spin 0.9s linear infinite;margin:10px auto}
    @keyframes spin{to{transform:rotate(360deg)}}

    .hide{display:none !important}
  </style>
</head>
<body>
  <div class="card">
    <div class="header">
      <img src="https://podcastpontifications.com/wp-content/themes/podcastpontifications.com/images/mylogo.png" alt="Logo" class="logo-img" />
      <h1>Thanks! We’re fetching your cleaned audio…</h1>
      <p class="muted">This can take a little bit — please keep this tab open.</p>
    </div>

    <div class="spinner" id="spinner" aria-hidden="true"></div>

    <div id="status" class="status">Confirming payment and preparing your download…</div>

    <div class="row" style="margin-top:14px">
      <button id="btnDownload" class="btn" disabled>Preparing…</button>
      <button id="btnRetry" class="btn secondary" type="button">Retry</button>
      <a id="btnMore" class="btn ghost" href="/voice-isolator.php" rel="noopener">Clean more files</a>
    </div>
  </div>

  <script nonce="<?php echo $nonce; ?>">
  (function(){
    const EXCHANGE_URL = "<?php echo $N8N_HOST . $EXCHG_PATH; ?>";
    const sessionId = "<?php echo $sessionId; ?>";

    const $ = (id)=>document.getElementById(id);
    const statusEl = $('status');
    const btn = $('btnDownload');
    const retry = $('btnRetry');

    function setStatus(msg, tone){ statusEl.className = 'status' + (tone? ' ' + tone : ''); statusEl.textContent = msg; }

    if(!sessionId){ setStatus('Missing session_id in URL. Please return from Stripe or contact support.', 'err'); document.getElementById('spinner').classList.add('hide'); btn.disabled = true; return; }

    retry.onclick = ()=> location.reload();

    function exchangeOnce(){
      return new Promise((resolve)=>{
        const xhr = new XMLHttpRequest();
        xhr.open('POST', EXCHANGE_URL, true);
        xhr.responseType = 'json';
        xhr.setRequestHeader('Accept','application/json');
        xhr.setRequestHeader('Content-Type','application/json');
        xhr.onload = ()=> resolve({ status:xhr.status, json: xhr.response || null });
        xhr.onerror = ()=> resolve({ status:0, json:null });
        xhr.send(JSON.stringify({ session_id: sessionId }));
      });
    }

    (async function poll(){
      const sleep = (ms)=> new Promise(r=>setTimeout(r, ms));
      let attempt = 0; const MAX = 60; // up to ~2 minutes
      while(attempt++ < MAX){
        const { status, json } = await exchangeOnce();
        const ok = status >= 200 && status < 300;
        const url = json?.download_url || json?.url || json?.file || json?.file_url || '';
        const done = json?.status === 'done' || json?.state === 'succeeded';

        if ((ok && url) || (done && url)){
          document.getElementById('spinner').classList.add('hide');
          btn.disabled = false;
          btn.textContent = json.filename ? ('Download ') : 'Download file';
          btn.onclick = ()=>{ try{ const a=document.createElement('a'); a.href=url; a.rel='noopener'; a.click(); }catch(e){ location.href = url; } };
          setStatus('Ready. Click to download your cleaned audio.', 'ok');
          if (json.expires_at || json.expiresAt) document.getElementById('expires').textContent = 'Expires: ' + (json.expires_at || json.expiresAt);
          return;
        }

        const delay = Math.max(1200, 1200*attempt + Math.floor((Math.random()*2-1)*400));
        setStatus('Still preparing your download…', '');
        await sleep(delay);
      }

      document.getElementById('spinner').classList.add('hide');
      setStatus('Still processing — please try the Retry button in a moment.', 'err');
      btn.disabled = true;
    })();
  })();
  </script>
</body>
</html>