<?php
// ─────────────────────────────────────────────
// includes/email_portfolio_delivery.php
// Die Portfolio-Lieferungs-E-Mail
// Enthält: Portfolio-Zusammenfassung,
//          Nächste Schritte + offizielle Links,
//          Empfohlene RCIC-Berater
// ─────────────────────────────────────────────

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/mailer.php';

function send_portfolio_delivery(int $clientId): bool {
    $db = C2CDatabase::get();

    // ── Daten laden ───────────────────────────
    $client = C2CDatabase::getClient($clientId);
    if (!$client) return false;

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

    // Ausgewählte Story
    $stmt = $db->prepare("SELECT * FROM story_variants WHERE client_id=? AND selected=1 LIMIT 1");
    $stmt->execute([$clientId]);
    $story = $stmt->fetch();
    if (!$story) {
        $stmt = $db->prepare("SELECT * FROM story_variants WHERE client_id=? ORDER BY id LIMIT 1");
        $stmt->execute([$clientId]);
        $story = $stmt->fetch();
    }

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

    // Nächste Schritte
    $stmt = $db->query("SELECT * FROM portfolio_next_steps WHERE active=1 ORDER BY sort_order");
    $nextSteps = $stmt->fetchAll();
    $stepsByCategory = [];
    foreach ($nextSteps as $step) {
        $stepsByCategory[$step['category']][] = $step;
    }

    // RCIC-Berater
    $stmt = $db->query("SELECT * FROM rcic_consultants WHERE active=1 ORDER BY sort_order");
    $rcics = $stmt->fetchAll();

    // Pathways
    $pathways = [];
    if ($analysis && !empty($analysis['pathways'])) {
        $pathways = json_decode($analysis['pathways'], true) ?? [];
        $pathways = array_slice($pathways, 0, 3); // Top 3
    }

    // ── E-Mail aufbauen ───────────────────────
    $name         = trim(($client['vorname'] ?? '') . ' ' . ($client['nachname'] ?? ''));
    $vorname      = $client['vorname'] ?? 'Liebe/r Interessent/in';
    $serviceName  = match($client['service_type'] ?? 'portfolio') {
        'starter' => 'Geschichte Starter',
        'family'  => 'Familien-Geschichte',
        default   => 'Vollständiges Portfolio',
    };
    $primaryPathway = $analysis['recommended_pathway'] ?? '';
    $provinces      = $analysis['recommended_provinces'] ?? '';

    $subject = "Dein Portfolio ist fertig — Come2Canada.Life";
    $body    = build_portfolio_email(
        name:          $name,
        vorname:       $vorname,
        serviceName:   $serviceName,
        primaryPathway:$primaryPathway,
        provinces:     $provinces,
        pathways:      $pathways,
        story:         $story,
        stepsByCategory: $stepsByCategory,
        rcics:         $rcics
    );

    // ── Senden (über c2c_send_mail / SMTP, nicht PHP mail()) ──
    // Das HTML wird direkt versendet — kein Template-Lookup,
    // weil der Body bereits fertig gerendert ist.
    $sentResult = c2c_send_html_directly(
        $client['email'],
        $name ?: $client['email'],
        $subject,
        $body,
        $clientId,
        'mail_portfolio_delivery'
    );

    $result = $sentResult['ok'] ?? false;

    // Status in DB aktualisieren
    if ($result) {
        $db->prepare("UPDATE clients SET status='delivered' WHERE id=?")
           ->execute([$clientId]);
        $db->prepare("UPDATE portfolios SET status='delivered', updated_at=NOW() WHERE client_id=?")
           ->execute([$clientId]);
    }

    return $result;
}

/**
 * Schickt fertiges HTML direkt per SMTP (umgeht das Template-Lookup von c2c_send_mail).
 * Loggt aber genauso in mail_log.
 */
function c2c_send_html_directly(
    string $to,
    string $toName,
    string $subject,
    string $htmlBody,
    ?int $clientId,
    string $logTemplate
): array {
    $db = C2CDatabase::get();

    $stmt = $db->prepare("
        INSERT INTO mail_log (client_id, to_email, to_name, subject, template, status)
        VALUES (?, ?, ?, ?, ?, 'queued')
    ");
    $stmt->execute([$clientId, $to, $toName, $subject, $logTemplate]);
    $mailId = (int)$db->lastInsertId();

    try {
        $smtp = new C2CSmtpClient(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS);
        $smtp->send(
            MAIL_FROM,
            MAIL_FROM_NAME,
            $to,
            $toName,
            $subject,
            $htmlBody
        );
        $db->prepare("UPDATE mail_log SET status='sent', sent_at=NOW() WHERE id=?")
           ->execute([$mailId]);
        return ['ok' => true, 'mail_id' => $mailId];
    } catch (Throwable $e) {
        $db->prepare("UPDATE mail_log SET status='failed', error=? WHERE id=?")
           ->execute([$e->getMessage(), $mailId]);
        error_log("c2c_send_html_directly Fehler an $to: " . $e->getMessage());
        return ['ok' => false, 'mail_id' => $mailId, 'error' => $e->getMessage()];
    }
}

// ─────────────────────────────────────────────
// E-Mail HTML aufbauen
// ─────────────────────────────────────────────
// ─────────────────────────────────────────────
// E-Mail HTML aufbauen — leichter Stil, einheitlich mit mail_freigabe.html
// ─────────────────────────────────────────────
function build_portfolio_email(
    string $name,
    string $vorname,
    string $serviceName,
    string $primaryPathway,
    string $provinces,
    array  $pathways,
    ?array $story,
    array  $stepsByCategory,
    array  $rcics
): string {

    $today = date('j. F Y');
    $logo  = 'https://christianwehrli.ca/c2c/assets/logo-black.png';

    // ── STORY ──────────────────────────────────
    $storyHtml = '';
    if ($story && !empty($story['full_story'])) {
        // Markdown-Light: # → starker Absatz, **bold**, *italic*, doppelte Newlines → Absatz
        $rendered = htmlspecialchars($story['full_story'], ENT_QUOTES, 'UTF-8');
        $rendered = preg_replace('/^#+\s+(.+)$/m', '<strong style="display:block;margin:18px 0 8px;color:#1a1a1a;">$1</strong>', $rendered);
        $rendered = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $rendered);
        $rendered = preg_replace('/(?<!\*)\*([^*\n]+)\*(?!\*)/', '<em>$1</em>', $rendered);
        $paragraphs = preg_split('/\n{2,}/', trim($rendered));
        $storyBody = '';
        foreach ($paragraphs as $p) {
            $storyBody .= '<p style="margin:0 0 14px;line-height:1.75;">' . nl2br(trim($p)) . '</p>';
        }

        $storyHtml = sprintf('
        <div style="background:#fdfaf3;border-left:3px solid #b13a2e;padding:24px 28px;margin:28px 0;border-radius:0 4px 4px 0;">
          <h2 style="font-size:1.3rem;margin:0 0 6px;color:#1a1a1a;font-weight:600;">%s</h2>
          <div style="font-style:italic;color:#b13a2e;font-size:14px;margin-bottom:18px;">%s</div>
          <div style="font-size:15px;color:#3a3a3a;">%s</div>
        </div>',
            htmlspecialchars($story['title'] ?? 'Deine Geschichte'),
            htmlspecialchars($story['subtitle'] ?? ''),
            $storyBody
        );
    }

    // ── EMPFOHLENER PATHWAY ────────────────────
    $pathwayBlock = '';
    if (!empty($primaryPathway)) {
        $provincesHtml = !empty($provinces)
            ? '<div style="font-size:14px;color:#6a6a6a;margin-top:8px;">📍 Empfohlene Provinzen: ' . htmlspecialchars($provinces) . '</div>'
            : '';
        $pathwayBlock = '
        <div style="margin:28px 0;padding-top:24px;border-top:1px solid #e6e0d4;">
          <div style="font-size:11px;letter-spacing:2px;text-transform:uppercase;color:#b13a2e;margin-bottom:10px;font-family:monospace;">Empfohlener Einwanderungsweg</div>
          <div style="font-size:1.2rem;color:#1a1a1a;font-weight:600;">' . htmlspecialchars($primaryPathway) . '</div>
          ' . $provincesHtml . '
        </div>';
    }

    // ── PATHWAY-TABELLE ─────────────────────────
    $pathwayRows = '';
    foreach ($pathways as $pw) {
        $score = (int)($pw['fit_score'] ?? 0);
        $bar   = str_repeat('█', (int)($score / 10)) . str_repeat('░', 10 - (int)($score / 10));
        $pathwayRows .= sprintf('
            <tr>
              <td style="padding:10px 14px;border-bottom:1px solid #f0ece2;vertical-align:top;">
                <strong style="color:#1a1a1a;font-size:14px;">%s</strong><br>
                <span style="font-size:12px;color:#6a6a6a;">%s</span>
              </td>
              <td style="padding:10px 14px;border-bottom:1px solid #f0ece2;text-align:center;vertical-align:top;">
                <span style="font-family:monospace;font-size:12px;color:#b13a2e;">%s</span><br>
                <span style="font-size:11px;color:#9a9a9a;">%d%%</span>
              </td>
              <td style="padding:10px 14px;border-bottom:1px solid #f0ece2;vertical-align:top;">
                <span style="font-size:13px;color:#3a3a3a;">%s</span>
              </td>
            </tr>',
            htmlspecialchars($pw['name'] ?? ''),
            htmlspecialchars($pw['program_code'] ?? ''),
            $bar, $score,
            htmlspecialchars($pw['rationale'] ?? '')
        );
    }
    $pathwayTableBlock = '';
    if (!empty($pathwayRows)) {
        $pathwayTableBlock = '
        <div style="margin:28px 0;padding-top:24px;border-top:1px solid #e6e0d4;">
          <div style="font-size:11px;letter-spacing:2px;text-transform:uppercase;color:#b13a2e;margin-bottom:14px;font-family:monospace;">Deine Einwanderungswege im Überblick</div>
          <table width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e6e0d4;border-radius:4px;border-collapse:separate;">
            <tr style="background:#fdfaf3;">
              <td style="padding:8px 14px;font-family:monospace;font-size:11px;letter-spacing:1px;color:#9a9a9a;text-transform:uppercase;">Programm</td>
              <td style="padding:8px 14px;font-family:monospace;font-size:11px;letter-spacing:1px;color:#9a9a9a;text-transform:uppercase;text-align:center;">Score</td>
              <td style="padding:8px 14px;font-family:monospace;font-size:11px;letter-spacing:1px;color:#9a9a9a;text-transform:uppercase;">Warum</td>
            </tr>
            ' . $pathwayRows . '
          </table>
        </div>';
    }

    // ── NÄCHSTE SCHRITTE / CHECKLISTE ──────────
    $catLabels = [
        'sofort'      => '⚡ Sofort erledigen',
        'kurzfristig' => '📅 In den nächsten Monaten',
        'ressourcen'  => '🔧 Nützliche Ressourcen',
        'links'       => '🔗 Offizielle Links',
    ];
    $stepsHtml = '';
    foreach ($catLabels as $cat => $label) {
        $steps = $stepsByCategory[$cat] ?? [];
        if (empty($steps)) continue;
        $stepsHtml .= sprintf('
            <tr><td colspan="2" style="padding:18px 0 8px;">
              <span style="font-size:13px;color:#b13a2e;font-weight:600;">%s</span>
            </td></tr>', $label);
        foreach ($steps as $s) {
            $link = !empty($s['url'])
                ? sprintf('<br><a href="%s" style="color:#b13a2e;font-size:12px;">%s</a>',
                    htmlspecialchars($s['url']),
                    htmlspecialchars($s['url_label'] ?: 'Mehr erfahren →'))
                : '';
            $stepsHtml .= sprintf('
                <tr>
                  <td style="padding:8px 12px 8px 0;vertical-align:top;width:18px;
                    border-bottom:1px solid #f0ece2;font-size:14px;color:#9a9a9a;">□</td>
                  <td style="padding:8px 0;border-bottom:1px solid #f0ece2;">
                    <strong style="color:#1a1a1a;font-size:14px;">%s</strong><br>
                    <span style="color:#6a6a6a;font-size:13px;line-height:1.6;">%s</span>
                    %s
                  </td>
                </tr>',
                htmlspecialchars($s['title']),
                htmlspecialchars($s['description'] ?? ''),
                $link
            );
        }
    }
    $stepsBlock = '';
    if (!empty($stepsHtml)) {
        $stepsBlock = '
        <div style="margin:28px 0;padding-top:24px;border-top:1px solid #e6e0d4;">
          <div style="font-size:11px;letter-spacing:2px;text-transform:uppercase;color:#b13a2e;margin-bottom:6px;font-family:monospace;">Deine Checkliste</div>
          <h2 style="font-size:1.3rem;margin:0 0 16px;color:#1a1a1a;font-weight:600;">Was jetzt zu tun ist</h2>
          <table width="100%" cellpadding="0" cellspacing="0">
            ' . $stepsHtml . '
          </table>
        </div>';
    }

    // ── RCIC-LISTE ─────────────────────────────
    $rcicCards = '';
    foreach ($rcics as $r) {
        $contactBits = [];
        if (!empty($r['phone']))    $contactBits[] = '📞 ' . htmlspecialchars($r['phone']);
        if (!empty($r['email']))    $contactBits[] = '<a href="mailto:' . htmlspecialchars($r['email']) . '" style="color:#b13a2e;text-decoration:none;">✉ ' . htmlspecialchars($r['email']) . '</a>';
        if (!empty($r['website']))  $contactBits[] = '<a href="' . htmlspecialchars($r['website']) . '" style="color:#b13a2e;text-decoration:none;">🔗 Website</a>';
        $contactRow = !empty($contactBits) ? '<div style="margin-top:8px;font-size:13px;color:#6a6a6a;line-height:1.7;">' . implode(' · ', $contactBits) . '</div>' : '';

        $location = trim(implode(', ', array_filter([$r['city'] ?? '', $r['province'] ?? ''])));
        $rcicCards .= sprintf('
            <tr><td style="padding:14px 0;border-bottom:1px solid #f0ece2;">
              <strong style="color:#1a1a1a;font-size:15px;">%s</strong>
              <span style="color:#9a9a9a;font-size:12px;margin-left:6px;">%s</span><br>
              <span style="font-size:13px;color:#6a6a6a;">%s%s%s</span>
              %s
            </td></tr>',
            htmlspecialchars($r['name'] ?? ''),
            htmlspecialchars($r['rcic_number'] ?? ''),
            htmlspecialchars($r['firm'] ?? ''),
            !empty($r['firm']) && !empty($location) ? ' · ' : '',
            htmlspecialchars($location),
            $contactRow
        );
    }
    if (empty($rcicCards)) {
        $rcicCards = '<tr><td style="padding:14px 0;color:#6a6a6a;font-style:italic;font-size:14px;">
            Bitte kontaktiere uns direkt — wir vermitteln dir gerne einen lizenzierten RCIC.
            <a href="mailto:' . MAIL_FROM . '" style="color:#b13a2e;">'.MAIL_FROM.'</a>
            </td></tr>';
    }
    $rcicBlock = '
        <div style="margin:28px 0;padding-top:24px;border-top:1px solid #e6e0d4;">
          <div style="font-size:11px;letter-spacing:2px;text-transform:uppercase;color:#b13a2e;margin-bottom:6px;font-family:monospace;">Lizenzierte Berater</div>
          <h2 style="font-size:1.3rem;margin:0 0 6px;color:#1a1a1a;font-weight:600;">Empfohlene RCIC-Consultants</h2>
          <p style="font-size:14px;color:#6a6a6a;margin:0 0 14px;line-height:1.65;">
            Diese Berater sind vom ICCRC lizenziert und sprechen Deutsch.
            Sie können dir bei Anträgen und Einreichungen helfen.
            Erwähne, dass du über Come2Canada.Life vermittelt wurdest.
          </p>
          <table width="100%" cellpadding="0" cellspacing="0">
            ' . $rcicCards . '
          </table>
          <p style="font-size:12px;color:#9a9a9a;margin-top:12px;">
            Lizenz prüfen: <a href="https://iccrc-crcic.ca/find-an-iccrc-member/" style="color:#b13a2e;">iccrc-crcic.ca</a>
          </p>
        </div>';

    // ── ZITAT (persönliche Note) ───────────────
    $quoteBlock = '
        <div style="margin:28px 0;padding:24px 28px;background:#fdfaf3;border-radius:6px;">
          <p style="font-style:italic;font-size:16px;color:#3a3a3a;line-height:1.65;margin:0 0 12px;">
            "Kanada hat mich nicht als Tourist akzeptiert. Es hat mich als Mensch angenommen —
            mit meiner Geschichte, meinem Akzent, und meinem Schweizer Hang zur Pünktlichkeit.
            Das wird es mit dir genauso tun."
          </p>
          <div style="font-size:12px;color:#9a9a9a;font-family:monospace;letter-spacing:1px;">
            — Christian Wehrli · SwissChris · Newmarket, Ontario
          </div>
        </div>';

    return <<<HTML
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Dein Portfolio — Come2Canada.Life</title>
</head>
<body style="margin:0;padding:0;background:#fdfaf3;font-family:Georgia,'Times New Roman',serif;color:#1a1a1a;">

<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background:#fdfaf3;padding:2rem 1rem;">
  <tr>
    <td align="center">

      <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="640" style="max-width:640px;background:#ffffff;border:1px solid #e6e0d4;border-radius:6px;">

        <!-- HEADER -->
        <tr>
          <td style="padding:2.5rem 2rem 1.5rem;text-align:center;">
            <img src="{$logo}" alt="Come2Canada.Life" width="200"
                 style="display:block;margin:0 auto 1rem;max-width:200px;height:auto;">
            <h1 style="margin:0;font-size:1.7rem;font-weight:600;color:#1a1a1a;line-height:1.25;">
              Dein persönliches Portfolio<br>ist bereit, {$vorname}.
            </h1>
            <div style="font-size:13px;color:#6a6a6a;margin-top:.6rem;font-family:monospace;letter-spacing:1px;text-transform:uppercase;">
              {$serviceName} · {$today}
            </div>
          </td>
        </tr>

        <!-- INTRO -->
        <tr>
          <td style="padding:0 2rem 1rem;font-size:16px;line-height:1.65;">
            <p>Ich habe dein Profil angeschaut, deine möglichen Wege nach Kanada recherchiert
            und deine Geschichte ausgearbeitet. Was du in den Händen hältst, ist mehr als
            ein Dokument — es ist der erste konkrete Schritt deiner Einwanderung.</p>

            {$storyHtml}
            {$pathwayBlock}
            {$pathwayTableBlock}
            {$stepsBlock}
            {$rcicBlock}
            {$quoteBlock}
          </td>
        </tr>

        <!-- FOOTER -->
        <tr>
          <td style="padding:1.5rem 2rem;border-top:1px solid #e6e0d4;font-size:12px;color:#6a6a6a;text-align:center;">
            come2canada.life · Storytelling und Recherche, keine Rechtsberatung
          </td>
        </tr>

      </table>

    </td>
  </tr>
</table>

</body>
</html>
HTML;
}
