<?php
// ═══════════════════════════════════════════════════════════
//  FICTION IGNITION — api/lib/mailer.php
//  Email sending via PHPMailer + SMTP
//  Install: composer require phpmailer/phpmailer
// ═══════════════════════════════════════════════════════════

declare(strict_types=1);

require_once __DIR__ . '/config.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception as MailException;

/**
 * Send an email using SMTP credentials from .env
 */
function fi_send_email(
    string $toEmail,
    string $toName,
    string $subject,
    string $htmlBody,
    string $textBody = ''
): bool {
    // Require autoloader (installed via Composer)
    $autoload = __DIR__ . '/../../vendor/autoload.php';
    if (!file_exists($autoload)) {
        error_log('PHPMailer not installed. Run: composer require phpmailer/phpmailer');
        return false;
    }
    require_once $autoload;

    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = env('MAIL_HOST', 'smtp.gmail.com');
        $mail->SMTPAuth   = true;
        $mail->Username   = env('MAIL_USERNAME');
        $mail->Password   = env('MAIL_PASSWORD');
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = (int) env('MAIL_PORT', '587');
        $mail->CharSet    = 'UTF-8';

        $mail->setFrom(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME', 'Fiction Ignition'));
        $mail->addAddress($toEmail, $toName);
        $mail->Subject  = $subject;
        $mail->isHTML(true);
        $mail->Body     = $htmlBody;
        $mail->AltBody  = $textBody ?: strip_tags($htmlBody);

        $mail->send();
        return true;
    } catch (MailException $e) {
        error_log('Mailer error: ' . $mail->ErrorInfo);
        return false;
    }
}

// ── Email templates ────────────────────────────────────────

function fi_email_verify_template(string $name, string $verifyUrl): string {
    $appUrl = env('APP_URL');
    return <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
  body { margin:0; padding:0; background:#f2ebe0; font-family:'Segoe UI',Arial,sans-serif; }
  .wrap { max-width:580px; margin:40px auto; background:#fff; border-radius:12px; overflow:hidden; box-shadow:0 4px 24px rgba(0,0,0,.1); }
  .header { background:#1b2e5e; padding:32px 40px; text-align:center; }
  .header img { height:52px; }
  .header h1 { color:#fff; font-size:1.5rem; margin:12px 0 0; font-family:Georgia,serif; }
  .body { padding:40px; }
  .body h2 { color:#1b2e5e; font-family:Georgia,serif; margin-top:0; }
  .body p { color:#4a5a7a; line-height:1.7; font-size:0.97rem; }
  .btn { display:inline-block; background:#e8610a; color:#fff !important; text-decoration:none;
         padding:14px 32px; border-radius:6px; font-weight:600; font-size:1rem;
         margin:20px 0; box-shadow:0 4px 16px rgba(232,97,10,.35); }
  .footer { background:#0e1726; padding:20px 40px; text-align:center; }
  .footer p { color:rgba(255,255,255,.4); font-size:0.78rem; margin:0; }
</style>
</head>
<body>
<div class="wrap">
  <div class="header">
    <h1>🔥 Fiction Ignition</h1>
  </div>
  <div class="body">
    <h2>Welcome, {$name}!</h2>
    <p>Thank you for creating your Fiction Ignition account. One quick step before you can start generating story prompts — please verify your email address.</p>
    <div style="text-align:center">
      <a href="{$verifyUrl}" class="btn">Verify My Email</a>
    </div>
    <p style="font-size:.85rem;color:#8a9ab0">This link expires in 24 hours. If you didn't create an account, you can safely ignore this email.</p>
    <p style="font-size:.85rem;color:#8a9ab0">Or paste this link into your browser:<br><a href="{$verifyUrl}" style="color:#e8610a;word-break:break-all">{$verifyUrl}</a></p>
  </div>
  <div class="footer">
    <p>© 2025 Fiction Ignition · By Mark Bogner</p>
  </div>
</div>
</body>
</html>
HTML;
}

function fi_email_welcome_template(string $name): string {
    $appUrl = env('APP_URL');
    return <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  body { margin:0; padding:0; background:#f2ebe0; font-family:'Segoe UI',Arial,sans-serif; }
  .wrap { max-width:580px; margin:40px auto; background:#fff; border-radius:12px; overflow:hidden; box-shadow:0 4px 24px rgba(0,0,0,.1); }
  .header { background:#1b2e5e; padding:32px 40px; text-align:center; }
  .header h1 { color:#fff; font-size:1.5rem; margin:0; font-family:Georgia,serif; }
  .body { padding:40px; }
  .body h2 { color:#1b2e5e; font-family:Georgia,serif; margin-top:0; }
  .body p { color:#4a5a7a; line-height:1.7; }
  .btn { display:inline-block; background:#e8610a; color:#fff !important; text-decoration:none; padding:14px 32px; border-radius:6px; font-weight:600; margin:20px 0; }
  .tier-box { background:#f2ebe0; border:1px solid rgba(27,46,94,.15); border-radius:8px; padding:16px 20px; margin:20px 0; }
  .tier-box strong { color:#1b2e5e; }
  .footer { background:#0e1726; padding:20px 40px; text-align:center; }
  .footer p { color:rgba(255,255,255,.4); font-size:.78rem; margin:0; }
</style>
</head>
<body>
<div class="wrap">
  <div class="header">
    <h1>🔥 Fiction Ignition</h1>
  </div>
  <div class="body">
    <h2>Your account is ready, {$name}!</h2>
    <p>Email verified ✓ — you're all set. Start generating story prompts right now.</p>
    <div class="tier-box">
      <strong>Your Plan: Free</strong><br>
      <span style="font-size:.9rem;color:#6a7a9a">3 prompts per day · All 15+ genres · Upgrade anytime</span>
    </div>
    <div style="text-align:center">
      <a href="{$appUrl}/app.html" class="btn">Open Fiction Ignition →</a>
    </div>
    <p style="font-size:.88rem;color:#8a9ab0">Upgrade to Writer ($6.99/mo) for 25 prompts/day, saved history, and exports. Or go Author Pro ($9.99/mo) for unlimited prompts and custom genres.</p>
  </div>
  <div class="footer">
    <p>© 2025 Fiction Ignition · By Mark Bogner · <a href="{$appUrl}/pricing.html" style="color:rgba(255,255,255,.5)">Pricing</a></p>
  </div>
</div>
</body>
</html>
HTML;
}

function fi_email_payment_confirm_template(string $name, string $planLabel, string $price): string {
    $appUrl = env('APP_URL');
    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<style>
  body { margin:0; background:#f2ebe0; font-family:'Segoe UI',Arial,sans-serif; }
  .wrap { max-width:580px; margin:40px auto; background:#fff; border-radius:12px; overflow:hidden; box-shadow:0 4px 24px rgba(0,0,0,.1); }
  .header { background:#1b2e5e; padding:32px 40px; text-align:center; }
  .header h1 { color:#fff; font-size:1.5rem; margin:0; font-family:Georgia,serif; }
  .body { padding:40px; }
  .body h2 { color:#1b2e5e; font-family:Georgia,serif; margin-top:0; }
  .body p { color:#4a5a7a; line-height:1.7; }
  .badge { display:inline-block; background:#e8610a; color:#fff; padding:6px 16px; border-radius:20px; font-weight:700; font-size:.9rem; margin:8px 0; }
  .btn { display:inline-block; background:#e8610a; color:#fff !important; text-decoration:none; padding:14px 32px; border-radius:6px; font-weight:600; margin:20px 0; }
  .footer { background:#0e1726; padding:20px 40px; text-align:center; }
  .footer p { color:rgba(255,255,255,.4); font-size:.78rem; margin:0; }
</style>
</head>
<body>
<div class="wrap">
  <div class="header"><h1>🔥 Fiction Ignition</h1></div>
  <div class="body">
    <h2>Subscription Confirmed! 🎉</h2>
    <p>Hi {$name}, your subscription has been activated.</p>
    <p><strong>Plan:</strong> <span class="badge">{$planLabel}</span><br>
    <strong>Billing:</strong> {$price}/month</p>
    <p>Your new features are active immediately. Open the app to start writing.</p>
    <div style="text-align:center">
      <a href="{$appUrl}/app.html" class="btn">Open Fiction Ignition →</a>
    </div>
    <p style="font-size:.85rem;color:#8a9ab0">You can cancel anytime from your account settings. Questions? Reply to this email.</p>
  </div>
  <div class="footer"><p>© 2025 Fiction Ignition · By Mark Bogner</p></div>
</div>
</body>
</html>
HTML;
}
