<?php
// ─────────────────────────────────────────────
// hq/client.php  —  Klient-Detail mit KI-Analyse + Kurzbio
// ─────────────────────────────────────────────

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/kurzbio.php';

// ── Auth: hq_sessions-Token (Cookie/URL) ODER C2C_SECRET ──
// Akzeptiert mehrere Auth-Quellen für maximale Robustheit:
//  1. ?token=... in URL (auch C2C_SECRET als Fallback)
//  2. Cookie 'c2c_hq_token' (von doLogin gesetzt)
//  3. Header 'X-C2C-Token' (für API-Calls)
$tokenCandidate = $_GET['token']
    ?? ($_COOKIE['c2c_hq_token'] ?? null)
    ?? ($_SERVER['HTTP_X_C2C_TOKEN'] ?? null);

$authOk = false;

if ($tokenCandidate) {
    // a) C2C_SECRET-Match (für Aufrufe aus dem HQ-Frontend mit URL-Param)
    if (defined('C2C_SECRET') && hash_equals(C2C_SECRET, $tokenCandidate)) {
        $authOk = true;
    } else {
        // b) hq_sessions-Lookup (für eingeloggte Browser-Session)
        try {
            $db = C2CDatabase::get();
            $stmt = $db->prepare("SELECT 1 FROM hq_sessions WHERE token=? AND expires_at>NOW() LIMIT 1");
            $stmt->execute([$tokenCandidate]);
            if ($stmt->fetch()) $authOk = true;
        } catch (Throwable $e) {
            // DB-Fehler — Auth schlägt fehl, aber Seite zeigt sauberen Hinweis
        }
    }
}

if (!$authOk) {
    http_response_code(401);
    echo '<!DOCTYPE html><html><head><title>Nicht angemeldet</title>';
    echo '<style>body{font-family:Georgia,serif;max-width:480px;margin:5rem auto;padding:2rem;color:#1a1a1a;line-height:1.6}h1{color:#b13a2e}a{color:#b13a2e}</style>';
    echo '</head><body>';
    echo '<h1>Nicht angemeldet</h1>';
    echo '<p>Diese Seite benötigt einen Login. Bitte melde dich im HQ neu an.</p>';
    echo '<p><a href="index.html">→ Zur HQ-Anmeldung</a></p>';
    echo '</body></html>';
    exit;
}

$clientId = (int)($_GET['id'] ?? 0);
if (!$clientId) { header('Location: index.html'); exit; }

$client   = C2CDatabase::getClient($clientId);
if (!$client) { header('Location: index.html?error=not_found'); exit; }

$db = C2CDatabase::get();

// Aktuelle Kurzbio laden
$kurzbio = C2CKurzbio::getCurrent($clientId);

// Anzahl Magic-Link-Zugriffe (für Status-Anzeige nach Freigabe)
$tokenInfo = null;
if (in_array($client['status'], ['released','paid','delivered'])) {
    $stmt = $db->prepare("
        SELECT created_at, expires_at, last_accessed_at, access_count
        FROM customer_tokens
        WHERE client_id = ? AND revoked = 0
        ORDER BY id DESC LIMIT 1
    ");
    $stmt->execute([$clientId]);
    $tokenInfo = $stmt->fetch();
}

// Mail-History für diesen Klienten (für Header-Statuszeile + Bio-Panel)
$stmt = $db->prepare("
    SELECT template, status, sent_at, created_at, to_email
    FROM mail_log
    WHERE client_id = ?
    ORDER BY id DESC
");
$stmt->execute([$clientId]);
$mailHistory = $stmt->fetchAll();

// Hilfs-Lookup: jüngste erfolgreich versendete Mail pro Template
$mailsByTemplate = [];
foreach ($mailHistory as $m) {
    if ($m['status'] === 'sent' && !isset($mailsByTemplate[$m['template']])) {
        $mailsByTemplate[$m['template']] = $m;
    }
}
$eingangMail   = $mailsByTemplate['mail_eingang']           ?? null;
$freigabeMail  = $mailsByTemplate['mail_freigabe']          ?? null;
$portfolioMail = $mailsByTemplate['mail_portfolio_delivery'] ?? null;

// Analyse laden
$stmt = $db->prepare("SELECT * FROM immigration_analysis WHERE client_id=? ORDER BY id DESC LIMIT 1");
$stmt->execute([$clientId]);
$analysis = $stmt->fetch();

// Stories laden
$stmt = $db->prepare("SELECT * FROM story_variants WHERE client_id=? ORDER BY variant_key");
$stmt->execute([$clientId]);
$stories = $stmt->fetchAll();

// Portfolio laden
$stmt = $db->prepare("SELECT * FROM portfolios WHERE client_id=?");
$stmt->execute([$clientId]);
$portfolio = $stmt->fetch();

// Ausgewählte Story für Header-Anzeige (welche wurde versandt?)
$selectedStory = null;
foreach ($stories as $s) {
    if (!empty($s['selected'])) { $selectedStory = $s; break; }
}
$variantLabel = [
    'abenteuer'    => '🏔️ Abenteuer',
    'karriere'     => '💼 Karriere',
    'familie'      => '👨‍👩‍👧 Familie',
    'gemeinschaft' => '🤝 Gemeinschaft',
    'neustart'     => '🌱 Neustart',
];

// Queue-Status
$stmt = $db->prepare("SELECT * FROM processing_queue WHERE client_id=? ORDER BY id DESC LIMIT 5");
$stmt->execute([$clientId]);
$queue = $stmt->fetchAll();

$formData = $client['form_data'] ?? [];
$name     = trim(($client['vorname'] ?? '') . ' ' . ($client['nachname'] ?? ''));

// Pathways decodieren
$pathways    = $analysis ? json_decode($analysis['pathways'] ?? '[]', true) : [];
$swissAdvs   = $analysis ? json_decode($analysis['swiss_advantages'] ?? '[]', true) : [];
$riskFactors = $analysis ? json_decode($analysis['risk_factors'] ?? '[]', true) : [];
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= htmlspecialchars($name) ?> — HQ</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Playfair+Display:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {
  --forest:#1a3a2a; --forest-mid:#2d5a3d; --maple:#c8392b;
  --gold:#c8a96e; --cream:#f5f0e8; --bg:#f0f2f0;
  --ink:#1e1e1e; --ink-mid:#555; --ink-light:#888;
  --border:#dde3dd; --white:#fff; --shadow:rgba(0,0,0,0.08);
  --radius:8px;
}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:Inter,sans-serif;background:var(--bg);color:var(--ink);font-size:14px;}

/* NAV */
.hq-nav{background:var(--forest);color:#fff;padding:12px 24px;display:flex;align-items:center;gap:16px;}
.hq-nav a{color:rgba(255,255,255,0.7);text-decoration:none;font-size:13px;}
.hq-nav a:hover{color:#fff;}
.hq-nav .sep{color:rgba(255,255,255,0.3);}
.hq-nav .current{color:#fff;font-weight:600;}

/* LAYOUT */
.page{max-width:1200px;margin:0 auto;padding:24px;}
.page-header{background:var(--white);border-radius:var(--radius);padding:24px 28px;
  margin-bottom:20px;display:flex;align-items:flex-start;justify-content:space-between;
  gap:16px;box-shadow:0 1px 3px var(--shadow);}
.client-name h1{font-family:'Playfair Display',serif;font-size:26px;color:var(--forest);}
.client-meta{display:flex;gap:12px;margin-top:6px;flex-wrap:wrap;}
.badge{padding:3px 10px;border-radius:20px;font-size:12px;font-weight:600;}
.badge-status-new{background:#fff3cd;color:#856404;}
.badge-status-analyzing{background:#cfe2ff;color:#084298;}
.badge-status-ready{background:#d1e7dd;color:#0f5132;}
.badge-status-delivered{background:#e0e0e0;color:#333;}
.badge-service{background:var(--cream);color:var(--forest);}

/* ACTIONS */
.action-bar{display:flex;gap:10px;flex-wrap:wrap;}
.btn{padding:9px 18px;border-radius:6px;border:none;cursor:pointer;font-size:13px;
  font-weight:600;font-family:Inter,sans-serif;transition:all 0.15s;display:inline-flex;
  align-items:center;gap:6px;text-decoration:none;}
.btn-primary{background:var(--forest);color:#fff;}
.btn-primary:hover{background:var(--forest-mid);}
.btn-danger{background:var(--maple);color:#fff;}
.btn-gold{background:var(--gold);color:var(--forest);}
.btn-outline{background:transparent;border:1.5px solid var(--border);color:var(--ink-mid);}
.btn-outline:hover{border-color:var(--forest);color:var(--forest);}
.btn:disabled{opacity:0.5;cursor:not-allowed;}

/* GRID */
.content-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;}
.full-width{grid-column:1/-1;}
@media(max-width:900px){.content-grid{grid-template-columns:1fr;}}

/* CARDS */
.card{background:var(--white);border-radius:var(--radius);box-shadow:0 1px 3px var(--shadow);overflow:hidden;}
.card-head{padding:16px 20px;border-bottom:1px solid var(--border);
  display:flex;align-items:center;justify-content:space-between;}
.card-head h3{font-size:14px;font-weight:600;color:var(--forest);}
.card-body{padding:20px;}

/* PROFILE TABLE */
.profile-table{width:100%;border-collapse:collapse;}
.profile-table tr td{padding:8px 0;border-bottom:1px solid var(--border);vertical-align:top;}
.profile-table tr:last-child td{border-bottom:none;}
.profile-table td:first-child{width:40%;color:var(--ink-light);font-size:13px;padding-right:12px;}
.profile-table td:last-child{font-size:14px;}

/* ANALYSIS */
.pathway-card{border:1px solid var(--border);border-radius:6px;padding:14px 16px;margin-bottom:12px;}
.pathway-name{font-weight:600;color:var(--forest);margin-bottom:6px;display:flex;
  align-items:center;justify-content:space-between;}
.fit-score{display:inline-flex;align-items:center;gap:6px;}
.score-bar{width:80px;height:6px;background:var(--border);border-radius:3px;overflow:hidden;}
.score-fill{height:100%;border-radius:3px;background:var(--gold);}
.score-fill.high{background:#2d8a4e;}
.score-fill.med{background:var(--gold);}
.score-fill.low{background:var(--maple);}
.pathway-detail{font-size:13px;color:var(--ink-mid);margin-bottom:4px;}
.gap-list{margin-top:8px;}
.gap-item{font-size:12px;background:#fff3cd;color:#856404;
  padding:2px 8px;border-radius:3px;display:inline-block;margin:2px;}

/* SWISS ADVANTAGES */
.adv-item{border-left:3px solid var(--gold);padding:10px 14px;margin-bottom:10px;background:var(--cream);}
.adv-title{font-weight:600;font-size:13px;color:var(--forest);}
.adv-desc{font-size:12px;color:var(--ink-mid);margin-top:3px;}
.adv-value{font-size:12px;color:#0f5132;margin-top:3px;font-style:italic;}

/* STORIES */
.story-tabs{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px;}
.story-tab{padding:7px 16px;border-radius:20px;border:1.5px solid var(--border);
  cursor:pointer;font-size:13px;background:transparent;font-family:Inter,sans-serif;transition:all 0.15s;}
.story-tab.active,.story-tab:hover{background:var(--forest);color:#fff;border-color:var(--forest);}
.story-tab.is-selected{border-color:#0f5132;border-width:2px;}
.story-tab.is-selected.active{background:#0f5132;border-color:#0f5132;}
.story-panel{display:none;}
.story-panel.active{display:block;}
.story-title{font-family:'Playfair Display',serif;font-size:20px;color:var(--forest);margin-bottom:6px;}
.story-subtitle{font-style:italic;color:var(--ink-mid);font-size:14px;margin-bottom:14px;}
.story-teaser{background:var(--cream);border-left:3px solid var(--gold);
  padding:12px 16px;font-size:14px;margin-bottom:16px;line-height:1.6;}
.story-body{white-space:pre-wrap;font-size:14px;line-height:1.75;color:var(--ink-mid);}
.story-select-btn{margin-top:12px;}

/* QUEUE */
.queue-item{display:flex;align-items:center;gap:10px;padding:8px 0;
  border-bottom:1px solid var(--border);font-size:13px;}
.queue-item:last-child{border-bottom:none;}
.q-status-done::before{content:'✓';color:#0f5132;}
.q-status-running::before{content:'⟳';color:#084298;animation:spin 1s linear infinite;}
.q-status-pending::before{content:'○';color:var(--ink-light);}
.q-status-failed::before{content:'✗';color:var(--maple);}
@keyframes spin{to{transform:rotate(360deg);}}

/* TOAST */
#toast{position:fixed;bottom:24px;right:24px;background:var(--forest);color:#fff;
  padding:12px 20px;border-radius:8px;font-size:14px;opacity:0;
  transition:opacity 0.3s;pointer-events:none;z-index:999;}
#toast.show{opacity:1;}

/* LOADING OVERLAY */
#loadingOverlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.4);
  z-index:1000;align-items:center;justify-content:center;}
#loadingOverlay.active{display:flex;}
.loading-box{background:#fff;border-radius:12px;padding:32px 40px;text-align:center;}
.loading-box h3{font-family:'Playfair Display',serif;color:var(--forest);margin-bottom:8px;}
.spinner{width:40px;height:40px;border:4px solid var(--border);
  border-top-color:var(--forest);border-radius:50%;animation:spin 0.8s linear infinite;
  margin:0 auto 16px;}
</style>
</head>
<body>

<!-- Navigation -->
<nav class="hq-nav">
  <a href="index.html">HQ</a>
  <span class="sep">/</span>
  <a href="index.html#klienten">Klienten</a>
  <span class="sep">/</span>
  <span class="current"><?= htmlspecialchars($name) ?></span>
</nav>

<!-- Loading Overlay -->
<div id="loadingOverlay">
  <div class="loading-box">
    <div class="spinner"></div>
    <h3>KI arbeitet...</h3>
    <p id="loadingMsg">Analyse wird durchgeführt</p>
  </div>
</div>

<div class="page">

  <!-- Page Header -->
  <div class="page-header">
    <div class="client-name">
      <h1><?= htmlspecialchars($name) ?></h1>
      <div class="client-meta">
        <span class="badge badge-status-<?= $client['status'] ?>"><?= ucfirst($client['status']) ?></span>
        <span class="badge badge-service"><?= htmlspecialchars(match($client['service_type']){
          'starter'=>'Geschichte Starter','family'=>'Familien-Geschichte',default=>'Vollständiges Portfolio'
        }) ?></span>
        <span style="color:var(--ink-light);font-size:13px;">
          📧 <?= htmlspecialchars($client['email']) ?>
        </span>
        <span style="color:var(--ink-light);font-size:13px;">
          🗓 <?= date('d.m.Y', strtotime($client['created_at'])) ?>
        </span>
      </div>
      <?php if ($eingangMail || $freigabeMail || $portfolioMail || $selectedStory): ?>
      <div style="margin-top:8px;font-size:12px;color:var(--ink-light);line-height:1.7;">
        <?php
          $parts = [];
          if ($eingangMail) {
              $parts[] = '<span title="Eingangsbestätigung an ' . htmlspecialchars($eingangMail['to_email']) . '">'
                       . '✉️ Eingang am ' . date('d.m.Y H:i', strtotime($eingangMail['sent_at'])) . '</span>';
          }
          if ($freigabeMail) {
              $parts[] = '<span title="Magic-Link an ' . htmlspecialchars($freigabeMail['to_email']) . '">'
                       . '🍁 Kurzbio am ' . date('d.m.Y H:i', strtotime($freigabeMail['sent_at']))
                       . ' an ' . htmlspecialchars($freigabeMail['to_email']) . '</span>';
          }
          if ($portfolioMail) {
              $parts[] = '<span title="Portfolio an ' . htmlspecialchars($portfolioMail['to_email']) . '">'
                       . '📂 Portfolio am ' . date('d.m.Y H:i', strtotime($portfolioMail['sent_at']))
                       . ' an ' . htmlspecialchars($portfolioMail['to_email']) . '</span>';
          }
          if ($selectedStory) {
              $lbl = $variantLabel[$selectedStory['variant_key']] ?? ucfirst($selectedStory['variant_key']);
              $parts[] = '<span style="color:#0f5132;font-weight:600;" title="Diese Story wurde versandt">'
                       . '✓ Story: ' . $lbl . '</span>';
          }
          echo implode(' · ', $parts);
        ?>
      </div>
      <?php endif; ?>
    </div>
    <div class="action-bar">
      <?php if (!$analysis): ?>
        <button class="btn btn-primary" onclick="triggerAnalysis(<?= $clientId ?>)">
          🔍 Analyse starten
        </button>
      <?php else: ?>
        <button class="btn btn-outline" onclick="triggerAnalysis(<?= $clientId ?>)">
          🔄 Neu analysieren
        </button>
      <?php endif; ?>

      <?php if ($analysis && empty($stories)): ?>
        <button class="btn btn-gold" onclick="triggerStories(<?= $clientId ?>, <?= $analysis['id'] ?>)">
          ✍️ Stories generieren
        </button>
      <?php elseif (!empty($stories)): ?>
        <button class="btn btn-outline" onclick="triggerStories(<?= $clientId ?>, <?= $analysis['id'] ?>)">
          🔄 Stories neu generieren
        </button>
      <?php endif; ?>

      <?php if (!empty($stories)): ?>
        <button class="btn btn-primary" onclick="triggerPortfolio(<?= $clientId ?>)">
          📄 Portfolio erstellen
        </button>
      <?php endif; ?>

      <?php if ($portfolio): ?>
        <button class="btn btn-gold" onclick="sendPortfolio(<?= $clientId ?>, '<?= htmlspecialchars($client['email']) ?>')"
          title="Portfolio-E-Mail mit Nächsten Schritten und RCIC-Liste senden">
          📬 Portfolio senden
        </button>
      <?php endif; ?>

      <a href="rcic.php" class="btn btn-outline" style="font-size:12px;padding:7px 14px;">
        👥 RCIC-Liste
      </a>
    </div>
  </div>

  <!-- ╭───────────────────────────────────╮ -->
  <!-- │ Kurzbiographie (Vorschau-Phase)   │ -->
  <!-- ╰───────────────────────────────────╯ -->
  <div class="card kurzbio-card" style="margin-bottom:1.5rem;border-left:3px solid var(--maple);">
    <div class="card-head">
      <h3>🍁 Kurzbiographie</h3>
      <?php if ($kurzbio): ?>
        <span style="font-size:12px;color:var(--ink-light);">
          v<?= (int)$kurzbio['version'] ?> · Status: <?= htmlspecialchars($kurzbio['status']) ?>
          <?= $kurzbio['updated_at'] ? ' · ' . date('d.m.Y H:i', strtotime($kurzbio['updated_at'])) : '' ?>
        </span>
      <?php endif; ?>
    </div>
    <div class="card-body">

    <?php if (!$kurzbio): ?>
      <p style="color:var(--ink-light);margin:0 0 1rem;">
        Noch keine Kurzbio generiert.
        Christian Wehrli liest die Geschichte und generiert eine Vorschau.
      </p>
      <button class="btn btn-primary" onclick="generateKurzbio(<?= $clientId ?>)">
        ✨ Kurzbio generieren
      </button>

    <?php elseif ($kurzbio['status'] === 'freigegeben'): ?>
      <!-- Bereits freigegeben → kompakte Anzeige -->
      <div style="background:#e7f3e8;border-left:3px solid #4a7d4f;padding:1rem 1.25rem;border-radius:0 6px 6px 0;margin-bottom:1rem;">
        <strong>✓ Kurzbio
          <?php if ($freigabeMail): ?>
            am <?= date('d.m.Y \u\m H:i', strtotime($freigabeMail['sent_at'])) ?>
            an <?= htmlspecialchars($freigabeMail['to_email']) ?> versandt.
          <?php else: ?>
            freigegeben.</strong> Mail an <?= htmlspecialchars($client['email']) ?>
          <?php endif; ?>
          <?php if ($freigabeMail): ?></strong><?php endif; ?>

        <?php if ($tokenInfo): ?>
          <div style="font-size:13px;color:var(--ink-light);margin-top:.4rem;">
            Magic-Link gültig bis <?= date('d.m.Y', strtotime($tokenInfo['expires_at'])) ?>
            <?php if ((int)$tokenInfo['access_count'] > 0): ?>
              · <strong style="color:#0f5132;"><?= (int)$tokenInfo['access_count'] ?>× geöffnet</strong>
              (zuletzt <?= date('d.m.Y H:i', strtotime($tokenInfo['last_accessed_at'])) ?>)
            <?php else: ?>
              · noch nicht geöffnet
            <?php endif; ?>
          </div>
        <?php endif; ?>
      </div>

      <details>
        <summary style="cursor:pointer;color:var(--ink-light);font-size:13px;margin-bottom:.5rem;">
          Bio-Text anzeigen
        </summary>
        <div id="kurzbio-display" style="background:var(--bg);padding:1rem;border-radius:6px;font-family:Georgia,serif;line-height:1.65;white-space:pre-wrap;font-size:14px;margin-top:.5rem;">
<?= htmlspecialchars($kurzbio['inhalt'] ?? '') ?>
        </div>
      </details>

      <div style="margin-top:1rem;">
        <button class="btn btn-outline" onclick="generateKurzbio(<?= $clientId ?>)" style="font-size:12px;">
          🔄 Neue Version generieren
        </button>
      </div>

    <?php else: ?>
      <!-- Status 'ready' (oder 'generating') — Edit-Bereich anzeigen -->
      <p style="margin:0 0 1rem;color:var(--ink-light);">
        Lies durch, redigiere bei Bedarf, dann <strong>freigeben</strong> — der Klient bekommt die Mail.
      </p>

      <textarea id="kurzbio-edit" rows="14"
        style="width:100%;font-family:Georgia,serif;font-size:14.5px;line-height:1.65;padding:1rem;
               border:1px solid var(--border);border-radius:6px;background:var(--bg);resize:vertical;"
      ><?= htmlspecialchars($kurzbio['inhalt'] ?? '') ?></textarea>

      <div style="display:flex;gap:.5rem;flex-wrap:wrap;margin-top:1rem;">
        <button class="btn btn-outline" onclick="saveKurzbio(<?= $clientId ?>)">
          💾 Speichern
        </button>
        <button class="btn btn-outline" onclick="generateKurzbio(<?= $clientId ?>)">
          🔄 Neu generieren
        </button>
        <button class="btn btn-primary" onclick="releaseClient(<?= $clientId ?>)" style="margin-left:auto;">
          ✉️ Freigeben &amp; Mail senden
        </button>
      </div>

      <div id="kurzbio-status" style="margin-top:.75rem;font-size:13px;color:var(--ink-light);"></div>
    <?php endif; ?>

    </div>
  </div>

  <div class="content-grid">

    <!-- Profil -->
    <div class="card">
      <div class="card-head">
        <h3>👤 Persönliches Profil</h3>
      </div>
      <div class="card-body">
        <table class="profile-table">
          <tr><td>Kanton</td><td><?= htmlspecialchars($client['canton'] ?? '—') ?></td></tr>
          <tr><td>Geburtsjahr</td><td><?= htmlspecialchars($formData['geburtsjahr'] ?? '—') ?></td></tr>
          <tr><td>Familie</td><td><?= htmlspecialchars($formData['familienstand'] ?? '—') ?></td></tr>
          <tr><td>Beruf</td><td><?= htmlspecialchars($formData['beruf_aktuell'] ?? '—') ?></td></tr>
          <tr><td>Ausbildung</td><td><?= htmlspecialchars($formData['ausbildung_hoechster'] ?? '—') ?></td></tr>
          <tr><td>Englisch</td><td><?= htmlspecialchars($formData['englisch_niveau'] ?? '—') ?></td></tr>
          <tr><td>Französisch</td><td><?= htmlspecialchars($formData['franzoesisch_niveau'] ?? '—') ?></td></tr>
          <tr><td>Zeitplan</td><td><?= htmlspecialchars($formData['zeitplan'] ?? '—') ?></td></tr>
          <tr><td>Eigenkapital</td><td><?= htmlspecialchars($formData['eigenkapital'] ?? '—') ?></td></tr>
          <tr><td>Provinz-Wunsch</td><td><?= htmlspecialchars(implode(', ', (array)($formData['provinz'] ?? []))) ?></td></tr>
          <tr><td>Kanada-Kontakte</td><td><?= htmlspecialchars($formData['kontakte_kanada'] ?? '—') ?></td></tr>
        </table>
      </div>
    </div>

    <!-- Analyse-Zusammenfassung -->
    <div class="card">
      <div class="card-head">
        <h3>🔍 KI-Analyse</h3>
        <?php if ($analysis): ?>
          <span style="font-size:12px;color:var(--ink-light);">
            <?= date('d.m.Y H:i', strtotime($analysis['created_at'])) ?>
          </span>
        <?php endif; ?>
      </div>
      <div class="card-body">
        <?php if ($analysis): ?>
          <p style="margin-bottom:14px;font-size:14px;line-height:1.6;">
            <?= htmlspecialchars($analysis['profile_summary'] ?? '') ?>
          </p>
          <table class="profile-table">
            <tr>
              <td>Empfohlener Weg</td>
              <td><strong><?= htmlspecialchars($analysis['recommended_pathway'] ?? '—') ?></strong></td>
            </tr>
            <tr>
              <td>Provinzen</td>
              <td><?= htmlspecialchars($analysis['recommended_provinces'] ?? '—') ?></td>
            </tr>
            <tr>
              <td>CRS-Schätzung</td>
              <td><?= $analysis['crs_estimate'] ? '<strong>'.$analysis['crs_estimate'].'</strong> Punkte' : '—' ?></td>
            </tr>
            <tr>
              <td>NOC-Codes</td>
              <td><?= htmlspecialchars($analysis['noc_codes'] ?? '—') ?></td>
            </tr>
          </table>
        <?php else: ?>
          <p style="color:var(--ink-light);text-align:center;padding:20px;">
            Noch keine Analyse. Klicken Sie auf "Analyse starten".
          </p>
        <?php endif; ?>
      </div>
    </div>

    <!-- Einwanderungswege -->
    <?php if (!empty($pathways)): ?>
    <div class="card full-width">
      <div class="card-head"><h3>🗺️ Einwanderungswege</h3></div>
      <div class="card-body">
        <?php foreach ($pathways as $pw): ?>
          <?php
            $score = (int)($pw['fit_score'] ?? 0);
            $scoreClass = $score >= 75 ? 'high' : ($score >= 50 ? 'med' : 'low');
          ?>
          <div class="pathway-card">
            <div class="pathway-name">
              <span><?= htmlspecialchars($pw['name'] ?? '') ?>
                <?php if (!empty($pw['program_code'])): ?>
                  <span style="font-size:12px;font-weight:400;color:var(--ink-light);">
                    (<?= htmlspecialchars($pw['program_code']) ?>)
                  </span>
                <?php endif; ?>
              </span>
              <div class="fit-score">
                <div class="score-bar">
                  <div class="score-fill <?= $scoreClass ?>" style="width:<?= $score ?>%"></div>
                </div>
                <span style="font-size:12px;font-weight:600;"><?= $score ?>%</span>
              </div>
            </div>
            <div class="pathway-detail"><?= htmlspecialchars($pw['rationale'] ?? '') ?></div>
            <?php if (!empty($pw['timeline_months'])): ?>
              <div style="font-size:12px;color:var(--ink-light);">
                ⏱ ~<?= $pw['timeline_months'] ?> Monate
              </div>
            <?php endif; ?>
            <?php if (!empty($pw['gaps'])): ?>
              <div class="gap-list">
                <?php foreach ((array)$pw['gaps'] as $gap): ?>
                  <span class="gap-item">⚠ <?= htmlspecialchars($gap) ?></span>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Swiss Advantages -->
    <?php if (!empty($swissAdvs)): ?>
    <div class="card">
      <div class="card-head"><h3>🇨🇭 Swiss-Vorteile für Kanada</h3></div>
      <div class="card-body">
        <?php foreach ($swissAdvs as $adv): ?>
          <div class="adv-item">
            <div class="adv-title"><?= htmlspecialchars($adv['title'] ?? '') ?></div>
            <div class="adv-desc"><?= htmlspecialchars($adv['description'] ?? '') ?></div>
            <?php if (!empty($adv['canadian_value'])): ?>
              <div class="adv-value">→ <?= htmlspecialchars($adv['canadian_value']) ?></div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Risk Factors -->
    <?php if (!empty($riskFactors)): ?>
    <div class="card">
      <div class="card-head"><h3>⚠️ Herausforderungen</h3></div>
      <div class="card-body">
        <?php foreach ($riskFactors as $risk): ?>
          <div style="border-left:3px solid var(--maple);padding:10px 14px;margin-bottom:10px;background:#fff5f5;">
            <div style="font-weight:600;font-size:13px;color:var(--maple);"><?= htmlspecialchars($risk['area'] ?? '') ?></div>
            <div style="font-size:13px;color:var(--ink-mid);margin-top:3px;"><?= htmlspecialchars($risk['description'] ?? '') ?></div>
            <?php if (!empty($risk['mitigation'])): ?>
              <div style="font-size:12px;color:#0f5132;margin-top:4px;">💡 <?= htmlspecialchars($risk['mitigation']) ?></div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Story-Varianten -->
    <?php if (!empty($stories)): ?>
    <div class="card full-width">
      <div class="card-head">
        <h3>✍️ Story-Varianten</h3>
        <?php if ($selectedStory): ?>
          <span style="font-size:13px;color:#0f5132;font-weight:600;background:#e7f3e8;padding:4px 10px;border-radius:12px;">
            ✓ Versandt: <?= htmlspecialchars($variantLabel[$selectedStory['variant_key']] ?? $selectedStory['variant_key']) ?>
          </span>
        <?php endif; ?>
      </div>
      <div class="card-body">
        <div class="story-tabs">
          <?php foreach ($stories as $i => $story): ?>
            <button class="story-tab <?= $i===0?'active':'' ?> <?= $story['selected']?'is-selected':'' ?>"
              onclick="showStoryTab('<?= $story['variant_key'] ?>', this)"
              <?= $story['selected'] ? 'title="Diese Story wurde dem Klienten gesendet"' : '' ?>>
              <?= $variantLabel[$story['variant_key']] ?? ucfirst($story['variant_key']) ?>
              <?php if ($story['selected']): ?>
                <span style="color:#0f5132;font-weight:700;margin-left:4px;">✓</span>
              <?php endif; ?>
            </button>
          <?php endforeach; ?>
        </div>

        <?php foreach ($stories as $i => $story): ?>
          <div class="story-panel <?= $i===0?'active':'' ?>"
               id="story-panel-<?= $story['variant_key'] ?>">
            <?php if ($story['selected'] && $portfolioMail): ?>
              <div style="background:#e7f3e8;border-left:3px solid #4a7d4f;padding:10px 14px;margin-bottom:14px;border-radius:0 4px 4px 0;font-size:13px;">
                ✓ Diese Story wurde am <strong><?= date('d.m.Y \u\m H:i', strtotime($portfolioMail['sent_at'])) ?></strong>
                an <strong><?= htmlspecialchars($portfolioMail['to_email']) ?></strong> versandt.
              </div>
            <?php elseif ($story['selected']): ?>
              <div style="background:#fff8e6;border-left:3px solid #b8860b;padding:10px 14px;margin-bottom:14px;border-radius:0 4px 4px 0;font-size:13px;">
                ✓ Diese Story ist ausgewählt — aber das Portfolio wurde noch nicht versandt.
              </div>
            <?php endif; ?>
            <div class="story-title"><?= htmlspecialchars($story['title'] ?? '') ?></div>
            <div class="story-subtitle"><?= htmlspecialchars($story['subtitle'] ?? '') ?></div>
            <div class="story-teaser"><?= htmlspecialchars($story['teaser'] ?? '') ?></div>
            <div class="story-body"><?= htmlspecialchars($story['full_story'] ?? '') ?></div>
            <?php if (!empty($story['advantages_block'])): ?>
              <div style="margin-top:16px;padding:14px;background:var(--cream);border-radius:6px;">
                <strong style="color:var(--forest);">Was <?= htmlspecialchars($client['vorname'] ?? 'dieser Mensch') ?> Kanada bringt:</strong>
                <div style="margin-top:8px;white-space:pre-wrap;font-size:13px;color:var(--ink-mid);">
                  <?= htmlspecialchars($story['advantages_block']) ?>
                </div>
              </div>
            <?php endif; ?>
            <div class="story-select-btn">
              <button class="btn <?= $story['selected']?'btn-gold':'btn-outline' ?>"
                onclick="selectStory(<?= $story['id'] ?>, <?= $clientId ?>)">
                <?= $story['selected'] ? '✓ Ausgewählt' : 'Diese Story wählen' ?>
              </button>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Queue Status -->
    <div class="card">
      <div class="card-head">
        <h3>⚙️ Verarbeitungs-Queue</h3>
        <button class="btn btn-outline" style="font-size:12px;padding:5px 12px;"
          onclick="location.reload()">Aktualisieren</button>
      </div>
      <div class="card-body">
        <?php if (empty($queue)): ?>
          <p style="color:var(--ink-light);font-size:13px;">Keine Tasks in der Queue.</p>
        <?php else: ?>
          <?php foreach ($queue as $task): ?>
            <div class="queue-item">
              <span class="q-status-<?= $task['status'] ?>"></span>
              <span><?= htmlspecialchars($task['task_type']) ?></span>
              <span style="color:var(--ink-light);margin-left:auto;">
                <?= date('H:i', strtotime($task['created_at'])) ?>
              </span>
              <?php if ($task['error_message']): ?>
                <span style="color:var(--maple);font-size:11px;" title="<?= htmlspecialchars($task['error_message']) ?>">!</span>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>

    <!-- Persönliche Geschichte (Rohdaten) -->
    <div class="card">
      <div class="card-head"><h3>📖 Persönliche Angaben</h3></div>
      <div class="card-body">
        <?php
        $storyFields = ['story_ich','story_stolz','story_kanada','story_besonderes','warum_text'];
        foreach ($storyFields as $f):
          if (!empty($formData[$f])):
        ?>
          <div style="margin-bottom:16px;">
            <div style="font-size:12px;font-weight:600;color:var(--ink-light);text-transform:uppercase;
              letter-spacing:0.5px;margin-bottom:4px;">
              <?= htmlspecialchars(str_replace('_',' ', $f)) ?>
            </div>
            <p style="font-size:14px;line-height:1.6;color:var(--ink-mid);">
              <?= htmlspecialchars($formData[$f]) ?>
            </p>
          </div>
        <?php endif; endforeach; ?>
      </div>
    </div>

  </div><!-- /content-grid -->
</div>

<div id="toast">Gespeichert ✓</div>

<script>
const API_BASE = '<?= C2C_API_BASE ?>';
const TOKEN    = '<?= C2C_SECRET ?>';

function showLoading(msg) {
  document.getElementById('loadingMsg').textContent = msg || 'Wird verarbeitet...';
  document.getElementById('loadingOverlay').classList.add('active');
}
function hideLoading() {
  document.getElementById('loadingOverlay').classList.remove('active');
}
function toast(msg) {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 3000);
}

async function apiCall(endpoint, params) {
  const url = API_BASE + endpoint + '?' + new URLSearchParams({...params, token: TOKEN});
  const res  = await fetch(url);
  return res.json();
}

async function triggerAnalysis(clientId) {
  showLoading('KI analysiert das Profil...');
  try {
    const data = await apiCall('analyze.php', { client_id: clientId });
    hideLoading();
    if (data.success) {
      toast('✓ Analyse abgeschlossen: ' + (data.recommended || ''));
      setTimeout(() => location.reload(), 1500);
    } else {
      alert('Fehler: ' + (data.error || 'Unbekannt'));
    }
  } catch(e) {
    hideLoading();
    alert('Verbindungsfehler: ' + e.message);
  }
}

async function triggerStories(clientId, analysisId) {
  showLoading('KI schreibt 3 Story-Varianten...');
  try {
    const data = await apiCall('stories.php', { client_id: clientId, analysis_id: analysisId });
    hideLoading();
    if (data.success) {
      toast('✓ ' + data.count + ' Stories generiert');
      setTimeout(() => location.reload(), 1500);
    } else {
      alert('Fehler: ' + (data.error || 'Unbekannt'));
    }
  } catch(e) {
    hideLoading();
    alert('Verbindungsfehler: ' + e.message);
  }
}

async function triggerPortfolio(clientId) {
  showLoading('Portfolio wird erstellt...');
  try {
    const data = await apiCall('portfolio.php', { client_id: clientId });
    hideLoading();
    if (data.success) {
      toast('✓ Portfolio erstellt');
      setTimeout(() => location.reload(), 1500);
    } else {
      alert('Fehler: ' + (data.error || 'Unbekannt'));
    }
  } catch(e) {
    hideLoading();
    alert('Verbindungsfehler: ' + e.message);
  }
}

async function sendPortfolio(clientId, email) {
  if (!confirm('Portfolio-E-Mail senden an:\n' + email + '\n\nEnthält: Portfolio, Nächste Schritte, RCIC-Liste')) return;
  showLoading('Portfolio-E-Mail wird gesendet...');
  try {
    const data = await apiCall('send_portfolio.php', { client_id: clientId });
    hideLoading();
    if (data.success) {
      toast('✓ ' + data.message);
      setTimeout(() => location.reload(), 2000);
    } else {
      alert('Fehler: ' + (data.error || 'Unbekannt'));
    }
  } catch(e) {
    hideLoading();
    alert('Verbindungsfehler: ' + e.message);
  }
}

async function selectStory(storyId, clientId) {
  await fetch(API_BASE + 'select_story.php?story_id=' + storyId + '&client_id=' + clientId + '&token=' + TOKEN);
  toast('Story ausgewählt ✓');
  setTimeout(() => location.reload(), 1000);
}

function showStoryTab(key, el) {
  document.querySelectorAll('.story-tab').forEach(t => t.classList.remove('active'));
  document.querySelectorAll('.story-panel').forEach(p => p.classList.remove('active'));
  el.classList.add('active');
  const panel = document.getElementById('story-panel-' + key);
  if (panel) panel.classList.add('active');
}

// ─── Kurzbio ──────────────────────────────────────────────

function setBioStatus(msg, color) {
  const el = document.getElementById('kurzbio-status');
  if (!el) return;
  el.style.color = color || 'var(--ink-light)';
  el.textContent = msg || '';
}

async function generateKurzbio(clientId) {
  if (!confirm('Neue Kurzbio generieren? Die Anthropic-API wird gerufen (~10 Sekunden).')) return;

  setBioStatus('⏳ Generiere — Anthropic-API arbeitet…');
  const url = API_BASE + 'regenerate-kurzbio.php?client_id=' + clientId + '&token=' + TOKEN;
  try {
    const r = await fetch(url);
    const d = await r.json();
    if (d.success) {
      toast('Kurzbio v' + d.version + ' generiert ✓');
      setTimeout(() => location.reload(), 800);
    } else {
      setBioStatus('Fehler: ' + (d.error || 'unbekannt'), '#b13a2e');
    }
  } catch (e) {
    setBioStatus('Verbindungsfehler: ' + e.message, '#b13a2e');
  }
}

async function saveKurzbio(clientId) {
  const textarea = document.getElementById('kurzbio-edit');
  if (!textarea) return;
  const inhalt = textarea.value.trim();
  if (!inhalt) { setBioStatus('Bio ist leer.', '#b13a2e'); return; }

  setBioStatus('⏳ Speichern…');
  try {
    const r = await fetch(API_BASE + 'save-kurzbio.php?token=' + TOKEN, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ client_id: clientId, inhalt })
    });
    const d = await r.json();
    if (d.success) {
      setBioStatus('✓ Gespeichert (' + d.length + ' Zeichen)', '#3B6D11');
    } else {
      setBioStatus('Fehler: ' + (d.error || 'unbekannt'), '#b13a2e');
    }
  } catch (e) {
    setBioStatus('Verbindungsfehler: ' + e.message, '#b13a2e');
  }
}

async function releaseClient(clientId) {
  // Erst speichern, dann freigeben
  const textarea = document.getElementById('kurzbio-edit');
  if (textarea) {
    const inhalt = textarea.value.trim();
    if (!inhalt) { setBioStatus('Bio ist leer — kann nicht freigegeben werden.', '#b13a2e'); return; }

    if (!confirm('Bio freigeben & Magic-Link-Mail an den Klienten senden?\n\nDanach kann der Klient die Bio sehen und über PayPal das Portfolio bestellen.')) return;

    // Erst speichern
    try {
      await fetch(API_BASE + 'save-kurzbio.php?token=' + TOKEN, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ client_id: clientId, inhalt })
      });
    } catch (e) {
      setBioStatus('Speichern fehlgeschlagen — Freigabe abgebrochen.', '#b13a2e');
      return;
    }
  }

  setBioStatus('⏳ Freigabe + Mailversand läuft…');
  try {
    const r = await fetch(API_BASE + 'release-client.php?token=' + TOKEN, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ client_id: clientId })
    });
    const d = await r.json();
    if (d.success) {
      toast('Bio freigegeben & Mail versendet ✓');
      setTimeout(() => location.reload(), 1000);
    } else {
      // Token wurde evtl. erstellt, aber Mail schlug fehl
      const msg = d.magic_link
        ? 'Mail-Versand fehlgeschlagen, aber Magic-Link existiert: ' + d.magic_link
        : ('Fehler: ' + (d.error || 'unbekannt'));
      setBioStatus(msg, '#b13a2e');
    }
  } catch (e) {
    setBioStatus('Verbindungsfehler: ' + e.message, '#b13a2e');
  }
}
</script>
</body>
</html>
