<?php
// Auto-detect PHPMailer location
$_base = dirname(__DIR__); // = studytrack root folder

// Try multiple possible paths
$_paths = [
    $_base . '/PHPMailer/src/',
    $_base . '/vendor/phpmailer/phpmailer/src/',
    $_base . '/phpmailer/src/',
];

$_found = null;
foreach ($_paths as $_p) {
    if (file_exists($_p . 'PHPMailer.php')) { $_found = $_p; break; }
}

if ($_found) {
    require_once $_found . 'Exception.php';
    require_once $_found . 'PHPMailer.php';
    require_once $_found . 'SMTP.php';
} else {
    // Fallback: composer autoload
    if (file_exists($_base . '/vendor/autoload.php')) {
        require_once $_base . '/vendor/autoload.php';
    } else {
        error_log("StudyTrack CRITICAL: PHPMailer not found under $_base");
    }
}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

if (!function_exists('sendEmail')) {
function sendEmail($to, $toName, $subject, $htmlBody) {
    if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
        error_log("StudyTrack: PHPMailer class not loaded, cannot send email to $to");
        return false;
    }
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER;
        $mail->Password   = SMTP_PASS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = SMTP_PORT;
        $mail->CharSet    = 'UTF-8';
        $mail->setFrom(SMTP_FROM, SMTP_FROM_NAME);
        $mail->addAddress($to, $toName);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("StudyTrack Mailer Error: " . $mail->ErrorInfo);
        return false;
    }
}
}

if (!function_exists('getEmailTemplate')) {
function getEmailTemplate($title, $content, $buttonText = '', $buttonUrl = '') {
    $btn = '';
    if ($buttonText && $buttonUrl) {
        $safeUrl = htmlspecialchars($buttonUrl, ENT_QUOTES, 'UTF-8');
        $btn = "
        <div style='text-align:center;margin:28px 0'>
          <a href='$safeUrl' style='background:linear-gradient(135deg,#6366f1,#a855f7);color:#fff;padding:14px 36px;border-radius:10px;text-decoration:none;font-weight:700;font-size:15px;display:inline-block'>
            $buttonText
          </a>
        </div>
        <div style='text-align:center;font-size:12px;color:#64748b;margin-top:8px'>
          If the button doesn't work, copy this link:<br>
          <span style='word-break:break-all;color:#6366f1'>$safeUrl</span>
        </div>";
    }
    return "<!DOCTYPE html><html><head><meta charset='UTF-8'></head>
<body style='margin:0;padding:20px;background:#0f0f1a;font-family:Arial,sans-serif'>
<div style='max-width:520px;margin:0 auto;background:#1a1a2e;border-radius:16px;overflow:hidden;border:1px solid #2d2d4e'>
  <div style='background:linear-gradient(135deg,#6366f1,#a855f7);padding:32px;text-align:center'>
    <h1 style='color:#fff;margin:0;font-size:24px;font-weight:700'>📚 StudyTrack</h1>
  </div>
  <div style='padding:32px'>
    <h2 style='color:#e2e8f0;margin:0 0 16px;font-size:20px'>$title</h2>
    <div style='color:#94a3b8;font-size:15px;line-height:1.7'>$content</div>
    $btn
  </div>
  <div style='padding:20px 32px;border-top:1px solid #2d2d4e;text-align:center;color:#64748b;font-size:13px'>
    © " . date('Y') . " StudyTrack. All rights reserved.
  </div>
</div></body></html>";
}
}

if (!function_exists('sendOTP')) {
function sendOTP($email, $name, $otp) {
    $escapedName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
    $content = "Hi <strong style='color:#e2e8f0'>$escapedName</strong>,<br><br>
Your email verification code is:<br>
<div style='background:#0f0f1a;border:2px dashed #6366f1;border-radius:12px;padding:24px;text-align:center;margin:20px 0'>
  <span style='font-size:40px;font-weight:800;color:#6366f1;letter-spacing:10px'>$otp</span>
</div>
This code expires in <strong style='color:#e2e8f0'>10 minutes</strong>. Do not share it with anyone.";
    return sendEmail($email, $name, 'StudyTrack - Verify Your Account', getEmailTemplate('Verify Your Account', $content));
}
}

if (!function_exists('sendPasswordReset')) {
function sendPasswordReset($email, $name, $resetUrl) {
    $escapedName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
    $content = "Hi <strong style='color:#e2e8f0'>$escapedName</strong>,<br><br>
We received a request to reset your StudyTrack password.<br><br>
Click the button below to set a new password. This link expires in <strong style='color:#e2e8f0'>1 hour</strong>.";
    return sendEmail($email, $name, 'StudyTrack - Password Reset', getEmailTemplate('Password Reset Request', $content, 'Reset My Password', $resetUrl));
}
}

// ============================================================
//  KEY 2 — නව Brevo Account (SMTP_USER2 / SMTP_PASS2)
//  sendPasswordResetSuccess, sendAccountDeleted, sendWeeklyReport,
//  sendFriendRequest, sendBiometricAdded, sendBiometricDeleted,
//  sendGoogleSignupWelcome, sendFacebookSignupWelcome,
//  sendManualSignupWelcome, sendSetPasswordLink
// ============================================================

if (!function_exists('_smtpSend2')) {
function _smtpSend2(string $toEmail, string $toName, string $subject, string $htmlBody): bool
{
    if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
        error_log('[StudyTrack KEY2] PHPMailer not loaded');
        return false;
    }
    if (!defined('SMTP_USER2') || !SMTP_USER2) {
        error_log('[StudyTrack KEY2] SMTP_USER2 not set in config.php');
        return false;
    }
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = defined('SMTP_HOST2') ? SMTP_HOST2 : 'smtp-relay.brevo.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER2;
        $mail->Password   = SMTP_PASS2;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = defined('SMTP_PORT2') ? SMTP_PORT2 : 587;
        $mail->CharSet    = 'UTF-8';
        $mail->Timeout    = 15;
        $mail->setFrom(
            defined('SMTP_FROM2') ? SMTP_FROM2 : SMTP_FROM,
            defined('SMTP_FROM_NAME2') ? SMTP_FROM_NAME2 : SMTP_FROM_NAME
        );
        $mail->addAddress($toEmail, $toName);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;
        $mail->AltBody = strip_tags(str_replace(['<br>','<br/>','</p>','</div>','</h2>','</li>'], "\n", $htmlBody));
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log('[StudyTrack KEY2] SMTP error: ' . $mail->ErrorInfo);
        return false;
    }
}
}

// ── Shared template helpers (KEY2) ──────────────────────────────────────────

if (!function_exists('_st2Wrap')) {
function _st2Wrap(string $body, string $preview = ''): string {
    $site = defined('SITE_NAME') ? SITE_NAME : 'StudyTrack';
    $url  = defined('SITE_URL')  ? SITE_URL  : '';
    $yr   = date('Y');
    $pre  = $preview ? '<div style="display:none;font-size:1px;color:#0f1117;max-height:0;overflow:hidden;">' . htmlspecialchars($preview) . '</div>' : '';
    return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#0f1117;font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Roboto,Arial,sans-serif;">'
. $pre
. '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#0f1117;padding:40px 16px;"><tr><td align="center">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;">
<tr><td style="background:linear-gradient(135deg,#1a1d2e,#16213e);border-radius:16px 16px 0 0;padding:28px 40px;text-align:center;border-bottom:1px solid rgba(99,102,241,0.25);">
  <div style="font-size:34px;margin-bottom:8px;">📚</div>
  <div style="font-size:21px;font-weight:800;color:#f8fafc;">' . htmlspecialchars($site) . '</div>
  <div style="font-size:12px;color:#475569;margin-top:4px;">A/L Study Tracker &middot; Sri Lanka</div>
</td></tr>
<tr><td style="background:#1a1d2e;padding:34px 40px;">' . $body . '</td></tr>
<tr><td style="background:#0d0f1a;border-radius:0 0 16px 16px;padding:22px 40px;text-align:center;border-top:1px solid rgba(255,255,255,0.04);">
  <p style="color:#1e293b;font-size:12px;margin:0 0 6px;">&copy; ' . $yr . ' ' . htmlspecialchars($site) . ' &mdash; Track your A/L journey.</p>
  <p style="font-size:12px;margin:0;"><a href="' . $url . '" style="color:#4f46e5;text-decoration:none;">Visit StudyTrack</a> &nbsp;&middot;&nbsp; <a href="' . $url . '/profile" style="color:#4f46e5;text-decoration:none;">Settings</a></p>
</td></tr>
</table></td></tr></table></body></html>';
}
}
if (!function_exists('_st2Btn')) {
function _st2Btn(string $url, string $label, string $bg = '#6366f1'): string {
    return '<div style="text-align:center;margin:26px 0;"><a href="' . htmlspecialchars($url) . '" style="display:inline-block;background:' . $bg . ';color:#fff;font-size:15px;font-weight:700;text-decoration:none;padding:13px 34px;border-radius:10px;">' . htmlspecialchars($label) . '</a></div>';
}
}
if (!function_exists('_st2Box')) {
function _st2Box(string $html, string $bg = 'rgba(99,102,241,0.08)', string $border = 'rgba(99,102,241,0.25)'): string {
    return '<div style="background:' . $bg . ';border:1px solid ' . $border . ';border-radius:10px;padding:15px 18px;margin:18px 0;"><p style="color:#94a3b8;font-size:13px;margin:0;line-height:1.8;">' . $html . '</p></div>';
}
}

// ── 1. Manual Signup Welcome (verify-otp.php) ────────────────────────────────

if (!function_exists('sendManualSignupWelcome')) {
function sendManualSignupWelcome(string $email, string $name): bool {
    $url  = defined('SITE_URL') ? SITE_URL : '';
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">Welcome to StudyTrack! 🎉</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br>Your email is verified and your account is ready. Let\'s start tracking! 🚀</p>
<div style="background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.2);border-radius:12px;padding:18px;margin:18px 0;">
  <p style="color:#94a3b8;font-size:13px;font-weight:600;margin:0 0 10px;">🚀 Get started:</p>
  <p style="color:#94a3b8;font-size:13px;margin:0;line-height:2.1;">📚 &nbsp;Log your study sessions<br>🎯 &nbsp;Set subject goals<br>📊 &nbsp;Track A/L progress<br>🔥 &nbsp;Build study streaks<br>👥 &nbsp;Connect with friends</p>
</div>
' . _st2Btn($url . '/dashboard', '🚀 Go to My Dashboard', '#6366f1') . '
<p style="color:#64748b;font-size:12px;text-align:center;margin:0;">Account: <strong style="color:#94a3b8;">' . htmlspecialchars($email) . '</strong></p>';
    return _smtpSend2($email, $name, '🎉 Welcome to StudyTrack — account verified!', _st2Wrap($body, 'Your StudyTrack account is ready!'));
}
}

// ── 2. Facebook Signup Welcome (fb-terms.php) ────────────────────────────────

if (!function_exists('sendFacebookSignupWelcome')) {
function sendFacebookSignupWelcome(string $email, string $name): bool {
    $url  = defined('SITE_URL') ? SITE_URL : '';
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">Welcome to StudyTrack! 🎉</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br>Your account was created using <strong style="color:#f8fafc;">Facebook Sign-In</strong>. You\'re all set!</p>
<div style="background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.2);border-radius:12px;padding:18px;margin:18px 0;">
  <p style="color:#94a3b8;font-size:13px;font-weight:600;margin:0 0 10px;">🚀 Get started:</p>
  <p style="color:#94a3b8;font-size:13px;margin:0;line-height:2.1;">📚 &nbsp;Log your study sessions<br>🎯 &nbsp;Set subject goals<br>📊 &nbsp;Track A/L progress<br>🔥 &nbsp;Build study streaks<br>👥 &nbsp;Connect with friends</p>
</div>
' . _st2Btn($url . '/dashboard', '🚀 Go to My Dashboard', '#6366f1') . '
<p style="color:#64748b;font-size:12px;text-align:center;margin:0;">Signed in with Facebook &mdash; <strong style="color:#94a3b8;">' . htmlspecialchars($email) . '</strong></p>';
    return _smtpSend2($email, $name, '🎉 Welcome to StudyTrack — your account is ready!', _st2Wrap($body, 'Your StudyTrack account is ready!'));
}
}

// ── 3. Google Signup Welcome (google-terms.php) ──────────────────────────────

if (!function_exists('sendGoogleSignupWelcome')) {
function sendGoogleSignupWelcome(string $email, string $name): bool {
    $url  = defined('SITE_URL') ? SITE_URL : '';
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">Welcome to StudyTrack! 🎉</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br>Your account was created using <strong style="color:#f8fafc;">Google Sign-In</strong>. You\'re all set!</p>
<div style="background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.2);border-radius:12px;padding:18px;margin:18px 0;">
  <p style="color:#94a3b8;font-size:13px;font-weight:600;margin:0 0 10px;">🚀 Get started:</p>
  <p style="color:#94a3b8;font-size:13px;margin:0;line-height:2.1;">📚 &nbsp;Log your study sessions<br>🎯 &nbsp;Set subject goals<br>📊 &nbsp;Track A/L progress<br>🔥 &nbsp;Build study streaks<br>👥 &nbsp;Connect with friends</p>
</div>
' . _st2Btn($url . '/dashboard', '🚀 Go to My Dashboard', '#6366f1') . '
<p style="color:#64748b;font-size:12px;text-align:center;margin:0;">Signed in with Google &mdash; <strong style="color:#94a3b8;">' . htmlspecialchars($email) . '</strong></p>';
    return _smtpSend2($email, $name, '🎉 Welcome to StudyTrack — your account is ready!', _st2Wrap($body, 'Your StudyTrack account is ready!'));
}
}

// ── 4. Friend Request (leaderboard.php) ─────────────────────────────────────

if (!function_exists('sendFriendRequest')) {
function sendFriendRequest(string $email, string $name, string $fromName, string $profileUrl = ''): bool {
    $url  = defined('SITE_URL') ? SITE_URL : '';
    if (!$profileUrl) $profileUrl = $url . '/leaderboard';
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">New Friend Request 👋</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br><strong style="color:#a5b4fc;">' . htmlspecialchars($fromName) . '</strong> sent you a friend request on StudyTrack!</p>
<div style="background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.2);border-radius:12px;padding:22px;text-align:center;margin:18px 0;">
  <div style="width:52px;height:52px;border-radius:50%;background:linear-gradient(135deg,#6366f1,#8b5cf6);margin:0 auto 10px;font-size:26px;line-height:52px;">👤</div>
  <div style="color:#f8fafc;font-size:16px;font-weight:700;">' . htmlspecialchars($fromName) . '</div>
  <div style="color:#64748b;font-size:13px;margin-top:4px;">wants to connect with you</div>
</div>
' . _st2Btn($profileUrl, '✅ View & Accept Request', '#6366f1')
. _st2Box('Study better together — compare progress and motivate each other! 📚');
    return _smtpSend2($email, $name, '👋 ' . $fromName . ' sent you a friend request', _st2Wrap($body, $fromName . ' wants to connect with you on StudyTrack'));
}
}

// ── 5. Weekly Study Report ───────────────────────────────────────────────────

if (!function_exists('sendWeeklyReport')) {
function sendWeeklyReport(string $email, string $name, array $stats = []): bool {
    $url        = defined('SITE_URL') ? SITE_URL : '';
    $hrs        = number_format((float)($stats['total_hours']    ?? 0), 1);
    $sessions   = (int)($stats['total_sessions'] ?? 0);
    $top        = htmlspecialchars($stats['top_subject'] ?? 'N/A');
    $streak     = (int)($stats['streak_days']   ?? 0);
    $goal       = min(100, max(0, (int)($stats['goal_percent'] ?? 0)));
    $week       = date('d M') . ' – ' . date('d M', strtotime('+6 days'));
    $barColor   = $goal >= 80 ? '#10b981' : ($goal >= 50 ? '#f59e0b' : '#ef4444');

    $rows = '';
    foreach (($stats['subjects'] ?? []) as $s) {
        $h = number_format((float)($s['hours'] ?? 0), 1);
        $rows .= '<tr><td style="color:#94a3b8;font-size:13px;padding:7px 10px;border-bottom:1px solid rgba(255,255,255,0.04);">' . htmlspecialchars($s['name'] ?? '') . '</td><td style="color:#f8fafc;font-size:13px;padding:7px 10px;border-bottom:1px solid rgba(255,255,255,0.04);text-align:right;font-weight:700;">' . $h . ' hrs</td></tr>';
    }
    $tbl = $rows ? '<p style="color:#94a3b8;font-size:13px;font-weight:600;margin:22px 0 6px;">Subject Breakdown</p><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;"><tr><th style="color:#64748b;font-size:11px;text-transform:uppercase;padding:5px 10px;text-align:left;border-bottom:1px solid rgba(255,255,255,0.08);">Subject</th><th style="color:#64748b;font-size:11px;text-transform:uppercase;padding:5px 10px;text-align:right;border-bottom:1px solid rgba(255,255,255,0.08);">Time</th></tr>' . $rows . '</table>' : '';

    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 4px;">Weekly Study Report 📊</h2>
<p style="color:#64748b;font-size:13px;margin:0 0 18px;">' . $week . '</p>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>, here\'s your weekly summary. Keep pushing! 💪</p>
<table role="presentation" width="100%" cellpadding="3" cellspacing="0" style="margin-bottom:18px;">
<tr>
  <td width="25%"><div style="background:rgba(99,102,241,0.1);border:1px solid rgba(99,102,241,0.2);border-radius:10px;padding:14px;text-align:center;"><div style="font-size:24px;font-weight:800;color:#a5b4fc;">' . $hrs . '</div><div style="font-size:11px;color:#64748b;margin-top:3px;">Hours</div></div></td>
  <td width="25%"><div style="background:rgba(16,185,129,0.1);border:1px solid rgba(16,185,129,0.2);border-radius:10px;padding:14px;text-align:center;"><div style="font-size:24px;font-weight:800;color:#6ee7b7;">' . $sessions . '</div><div style="font-size:11px;color:#64748b;margin-top:3px;">Sessions</div></div></td>
  <td width="25%"><div style="background:rgba(249,115,22,0.1);border:1px solid rgba(249,115,22,0.2);border-radius:10px;padding:14px;text-align:center;"><div style="font-size:24px;font-weight:800;color:#fdba74;">' . $streak . '</div><div style="font-size:11px;color:#64748b;margin-top:3px;">Streak 🔥</div></div></td>
  <td width="25%"><div style="background:rgba(245,158,11,0.1);border:1px solid rgba(245,158,11,0.2);border-radius:10px;padding:14px;text-align:center;"><div style="font-size:12px;font-weight:800;color:#fcd34d;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">' . $top . '</div><div style="font-size:11px;color:#64748b;margin-top:3px;">Top Subject</div></div></td>
</tr></table>
<p style="color:#94a3b8;font-size:13px;font-weight:600;margin:0 0 7px;">Weekly Goal &mdash; <span style="color:#f8fafc;">' . $goal . '%</span></p>
<div style="background:rgba(255,255,255,0.06);border-radius:5px;height:9px;overflow:hidden;margin-bottom:22px;"><div style="background:' . $barColor . ';width:' . $goal . '%;height:100%;border-radius:5px;"></div></div>
' . $tbl . _st2Btn($url . '/report', '📈 View Full Report', '#6366f1');
    return _smtpSend2($email, $name, '📊 Your Weekly Study Report — ' . $week, _st2Wrap($body, 'You studied ' . $hrs . ' hrs this week'));
}
}

// ── 6. Biometric Added (webauthn.php verify-register) ───────────────────────

if (!function_exists('sendBiometricAdded')) {
function sendBiometricAdded(string $email, string $name, string $deviceName = 'Unknown Device'): bool {
    $url  = defined('SITE_URL') ? SITE_URL : '';
    $time = date('D, d M Y  H:i T');
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">Biometric login enabled 🔐</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br>A new passkey was registered on your account.</p>
' . _st2Box('📱 <strong style="color:#f8fafc;">Device:</strong> ' . htmlspecialchars($deviceName) . '<br>🕐 <strong style="color:#f8fafc;">Time:</strong> ' . $time . '<br>📧 <strong style="color:#f8fafc;">Account:</strong> ' . htmlspecialchars($email), 'rgba(16,185,129,0.08)', 'rgba(16,185,129,0.25)') . '
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;">You can now sign in with fingerprint or face — no password needed! ✨</p>
' . _st2Btn($url . '/profile', '⚙️ Manage Devices', '#10b981')
. _st2Box('⚠️ If you did NOT add this device, <a href="' . $url . '/profile" style="color:#ef4444;font-weight:600;">remove it immediately</a> and change your password.', 'rgba(239,68,68,0.07)', 'rgba(239,68,68,0.2)');
    return _smtpSend2($email, $name, '🔐 New biometric login added to your account', _st2Wrap($body, 'New passkey registered: ' . $deviceName));
}
}

// ── 7. Biometric Deleted (webauthn.php remove-credential) ───────────────────

if (!function_exists('sendBiometricDeleted')) {
function sendBiometricDeleted(string $email, string $name, string $deviceName = 'Unknown Device'): bool {
    $url  = defined('SITE_URL') ? SITE_URL : '';
    $time = date('D, d M Y  H:i T');
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">Biometric login removed 🗑️</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br>A passkey was removed from your StudyTrack account.</p>
' . _st2Box('📱 <strong style="color:#f8fafc;">Device:</strong> ' . htmlspecialchars($deviceName) . '<br>🕐 <strong style="color:#f8fafc;">Removed at:</strong> ' . $time . '<br>📧 <strong style="color:#f8fafc;">Account:</strong> ' . htmlspecialchars($email), 'rgba(239,68,68,0.07)', 'rgba(239,68,68,0.25)') . '
' . _st2Btn($url . '/profile', '⚙️ Manage Devices', '#6366f1')
. _st2Box('⚠️ If you did NOT remove this device, please <a href="' . $url . '/forgot-password" style="color:#ef4444;font-weight:600;">reset your password immediately</a>.', 'rgba(245,158,11,0.07)', 'rgba(245,158,11,0.2)');
    return _smtpSend2($email, $name, '🗑️ Biometric login removed from your account', _st2Wrap($body, 'A passkey was removed from your account'));
}
}

// ── 8. Password Reset Success (reset-password.php) ──────────────────────────

if (!function_exists('sendPasswordResetSuccess')) {
function sendPasswordResetSuccess(string $email, string $name): bool {
    $url  = defined('SITE_URL') ? SITE_URL : '';
    $time = date('D, d M Y  H:i T');
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">Password changed ✅</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br>Your password was just updated.</p>
' . _st2Box('🕐 <strong style="color:#f8fafc;">Changed at:</strong> ' . $time . '<br>📧 <strong style="color:#f8fafc;">Account:</strong> ' . htmlspecialchars($email), 'rgba(16,185,129,0.08)', 'rgba(16,185,129,0.25)') . '
' . _st2Btn($url . '/login', '🔓 Sign In', '#10b981')
. _st2Box('⚠️ If you did NOT change this, <a href="' . $url . '/forgot-password" style="color:#ef4444;font-weight:600;">reset it immediately</a>.', 'rgba(239,68,68,0.07)', 'rgba(239,68,68,0.2)');
    return _smtpSend2($email, $name, '✅ Your StudyTrack password has been changed', _st2Wrap($body, 'Your password was updated'));
}
}

// ── 9. Account Deleted (profile.php) ────────────────────────────────────────

if (!function_exists('sendAccountDeleted')) {
function sendAccountDeleted(string $email, string $name): bool {
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">Account deleted 👋</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br>Your StudyTrack account and all data have been permanently deleted.</p>
' . _st2Box('🗑️ All study logs, goals, and progress removed.<br>📧 This email is no longer linked to any account.', 'rgba(239,68,68,0.07)', 'rgba(239,68,68,0.25)') . '
<p style="color:#94a3b8;font-size:14px;text-align:center;margin:18px 0;">We\'re sad to see you go. 😢 You\'re always welcome back!</p>
' . _st2Box('⚠️ If you did NOT request this, contact us immediately.', 'rgba(245,158,11,0.07)', 'rgba(245,158,11,0.2)');
    return _smtpSend2($email, $name, '👋 Your StudyTrack account has been deleted', _st2Wrap($body, 'Account permanently deleted'));
}
}

// ── 10. Set Password Link ────────────────────────────────────────────────────

if (!function_exists('sendSetPasswordLink')) {
function sendSetPasswordLink(string $email, string $name, string $setUrl): bool {
    $expiry = defined('RESET_EXPIRY_HOURS') ? RESET_EXPIRY_HOURS : 1;
    $body = '
<h2 style="color:#f8fafc;font-size:20px;font-weight:700;margin:0 0 8px;">Set your password 🔒</h2>
<p style="color:#94a3b8;font-size:14px;margin:0 0 18px;line-height:1.7;">Hi <strong style="color:#f8fafc;">' . htmlspecialchars($name) . '</strong>,<br>Click below to add a password. Expires in <strong style="color:#f8fafc;">' . (int)$expiry . ' hour(s)</strong>.</p>
' . _st2Btn($setUrl, '🔒 Set My Password', '#8b5cf6') . '
<p style="color:#64748b;font-size:12px;text-align:center;margin:-8px 0 16px;">Or copy: <span style="color:#7c3aed;word-break:break-all;">' . htmlspecialchars($setUrl) . '</span></p>
' . _st2Box('⚠️ If you did NOT request this, ignore this email.', 'rgba(239,68,68,0.07)', 'rgba(239,68,68,0.2)');
    return _smtpSend2($email, $name, '🔒 Set a password for your StudyTrack account', _st2Wrap($body, 'Add a password to your account'));
}
}
