<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require_once __DIR__ . '/PHPMailer/Exception.php';
require_once __DIR__ . '/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/SMTP.php';

/**
 * Reliably detect HTTPS on cPanel / Cloudflare / reverse-proxy setups.
 * Checks $SERVER['HTTPS'], X-Forwarded-Proto, and port 443.
 */
function _nroi_is_https(): bool
{
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true; // Standard: Apache sets HTTPS='on' or HTTPS='1'
    }
    if (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') {
        return true; // Cloudflare / load-balancer proxy
    }
    if (($_SERVER['HTTP_X_FORWARDED_SSL'] ?? '') === 'on') {
        return true; // Some reverse proxies
    }
    if (($_SERVER['SERVER_PORT'] ?? '') == '443') {
        return true; // Direct HTTPS port
    }
    return false;
}

function sendEmailConfirmation($toEmail, $fullName, $token)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $fullName);

        $mail->isHTML(true);
        $mail->Subject = 'Confirm Your Email - NROI Portal';

        $protocol = _nroi_is_https() ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'pointscard.nroi.net';

        $currentPath = $_SERVER['REQUEST_URI'] ?? '/api/register.php';
        $baseDir = dirname(dirname($currentPath));
        if ($baseDir === '\\' || $baseDir === '/')
            $baseDir = '';

        $confirmLink = "$protocol://$host" . $baseDir . "/api/confirm_email.php?token=$token";

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #1e293b; text-align: center;'>Email Confirmation Required</h2>
                <p>Hello <strong>$fullName</strong>,</p>
                <p>Thank you for registering with the NROI Portal. To complete your registration and link your email to your account, please click the button below:</p>
                <div style='text-align: center; margin: 30px 0;'>
                    <a href='$confirmLink' style='background-color: #020617; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; display: inline-block;'>Confirm Email</a>
                </div>
                <p style='color: #64748b; font-size: 0.9rem;'>If you did not create an account, please ignore this email.</p>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

function sendOTP($toEmail, $fullName, $otp)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $fullName);

        $mail->isHTML(true);
        $mail->Subject = "$otp is your NROI Password Reset Code";

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #1e293b; text-align: center;'>Password Reset Code</h2>
                <p>Hello <strong>$fullName</strong>,</p>
                <p>You requested to reset your password. Use the following code to proceed:</p>
                <div style='text-align: center; margin: 30px 0;'>
                    <span style='font-size: 32px; font-weight: bold; letter-spacing: 5px; color: #020617; background: #f1f5f9; padding: 10px 20px; border-radius: 8px;'>$otp</span>
                </div>
                <p style='color: #64748b; font-size: 0.9rem;'>This code will expire in 10 minutes.</p>
                <p style='color: #64748b; font-size: 0.9rem;'>If you did not request this, please secure your account.</p>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("OTP Email could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

function sendMatchNotification($toEmail, $fullName, $status, $matchName, $schedule, $location, $reason = '', $reviewerRole = '', $deductionPoints = 0, $remainingPoints = null, $prevStatus = '')
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $fullName);

        $mail->isHTML(true);
        $mail->Subject = "Match Call-Up Update: $status";

        // Build role label for messages (e.g. "AC", "AAC", "Admin", "RM")
        $roleMap = ['AC' => 'AC', 'AAC' => 'AAC', 'ADMIN' => 'Admin', 'RM' => 'Range Master'];
        $roleKey = strtoupper(trim($reviewerRole));
        $roleLabel = !empty($roleKey) ? ($roleMap[$roleKey] ?? ucfirst(strtolower($reviewerRole))) : '';
        $byRole = $roleLabel !== '' ? " by $roleLabel" : '';

        $statusMessage = '';
        if (strtolower($status) === 'standby') {
            $statusMessage = 'You are currently on standby for this match.';
        } elseif (strtolower($status) === 'approved') {
            $statusMessage = 'You have been approved to join this match.';
        } elseif (strtolower($status) === 'declined') {
            $statusMessage = "Your signification for this match has been declined$byRole.";
        } elseif (strtolower($status) === 'withdrawn') {
            $statusMessage = "You have been withdrawn from this match$byRole.";
        } elseif (strtolower($status) === 'withdrawal rejected') {
            $displayPrev = !empty($prevStatus) ? ucfirst($prevStatus) : 'Active';
            $statusMessage = "Your withdrawal request has been rejected$byRole. Your signification status for the match <strong>$matchName</strong> has been returned to <strong>$displayPrev</strong>.";
        } else {
            $statusMessage = "Your status for this match has been updated to: $status.";
        }

        $reasonBlock = '';
        if (!empty($reason)) {
            $escapedReason = htmlspecialchars($reason);
            $reasonBlock = "
                <div style='padding: 12px 0; margin: 16px 0;'>
                    <p style='margin: 0 0 6px 0; font-size: 0.8rem; font-weight: 700; color: #92400e;'>REASON</p>
                    <p style='margin: 0; font-size: 0.9rem; color: #7c2d12;'>$escapedReason</p>
                </div>";
        }

        $pointsBlock = '';
        if (strtolower($status) === 'withdrawn' && ($deductionPoints > 0 || $remainingPoints !== null)) {
            $pointsBlock = "
                <div style='background: #fef2f2; border: 1px solid #fee2e2; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                    <h4 style='margin: 0 0 10px 0; color: #991b1b; font-size: 0.95rem; border-bottom: 1px solid #fee2e2; padding-bottom: 8px;'>Points Summary</h4>";

            if ($deductionPoints > 0) {
                $pointsBlock .= "<p style='margin: 5px 0; color: #dc2626;'><strong>Deducted Points (Demerit):</strong> -" . number_format($deductionPoints, 2) . "</p>";
            }

            if ($remainingPoints !== null) {
                $pointsBlock .= "<p style='margin: 5px 0; color: #1e293b;'><strong>Current Total Points:</strong> " . number_format($remainingPoints, 2) . "</p>";
            }

            $pointsBlock .= "</div>";
        }

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #1e293b; text-align: center;'>Match Call-Up Update</h2>
                <p>Hello <strong>$fullName</strong>,</p>
                <p>$statusMessage</p>
                $reasonBlock
                $pointsBlock
                <div style='background: #f8fafc; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                    <p style='margin: 5px 0;'><strong>Match Name:</strong> $matchName</p>
                    <p style='margin: 5px 0;'><strong>Schedule:</strong> $schedule</p>
                    <p style='margin: 5px 0;'><strong>Location:</strong> $location</p>
                </div>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Match Notification Email could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

function sendRmAssignmentNotification($toEmail, $fullName, $matchName, $matchLevel, $disciplines, $schedule, $location, $isUpdate = false)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $fullName);

        $mail->isHTML(true);

        $actionWord = $isUpdate ? 'Updated' : 'Assigned';
        $mail->Subject = "Range Master $actionWord: $matchName";

        $introLine = $isUpdate
            ? "The match details for a match you are assigned to as <strong>Range Master</strong> have been updated."
            : "You have been assigned as the <strong>Range Master</strong> for an upcoming match.";

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #1e293b; text-align: center;'>Range Master $actionWord</h2>
                <p>Hello <strong>$fullName</strong>,</p>
                <p>$introLine</p>
                <div style='background: #f0f4ff; padding: 18px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #1e3a8a;'>
                    <p style='margin: 6px 0;'><strong>Match Name:</strong> $matchName</p>
                    <p style='margin: 6px 0;'><strong>Level:</strong> $matchLevel</p>
                    <p style='margin: 6px 0;'><strong>Disciplines:</strong> $disciplines</p>
                    <p style='margin: 6px 0;'><strong>Schedule:</strong> $schedule</p>
                    <p style='margin: 6px 0;'><strong>Location:</strong> $location</p>
                </div>
                <p>As the Range Master, you are responsible for overseeing the match operations. Please log in to the NROI Portal or app for further instructions.</p>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->AltBody = "Range Master $actionWord: $matchName\n\nMatch: $matchName\nLevel: $matchLevel\nDisciplines: $disciplines\nSchedule: $schedule\nLocation: $location\n\nLog in to the NROI Portal for details.";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("RM Assignment Email could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

function sendNewMatchNotification($toEmail, $fullName, $matchName, $schedule, $location, $matchLevel, $discipline, $rmName)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $fullName);

        $mail->isHTML(true);
        $mail->Subject = "New Upcoming Match: $matchName";

        $rmDisplay = !empty($rmName) ? $rmName : 'TBA';

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #1e293b; text-align: center;'>New Upcoming Match</h2>
                <p>Hello <strong>$fullName</strong>,</p>
                <p>A new match has been scheduled and is now available for signification. Here are the details:</p>
                <div style='background: #f8fafc; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                    <p style='margin: 5px 0;'><strong>Match Name:</strong> $matchName</p>
                    <p style='margin: 5px 0;'><strong>Level:</strong> $matchLevel</p>
                    <p style='margin: 5px 0;'><strong>Discipline:</strong> $discipline</p>
                    <p style='margin: 5px 0;'><strong>Range Master:</strong> $rmDisplay</p>
                    <p style='margin: 5px 0;'><strong>Schedule:</strong> $schedule</p>
                    <p style='margin: 5px 0;'><strong>Location:</strong> $location</p>
                </div>
                <p>Log in to the NROI Portal or app to view more details and signify your intent to join.</p>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("New Match Notification Email could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

/**
 * Send an email notification when a new notification message or reply is received.
 *
 * @param string $toEmail      Recipient email address
 * @param string $toName       Recipient full name
 * @param string $fromName     Sender's display name (may be 'AC/AAC' for anonymous officer sends)
 * @param string $subject      The message subject line
 * @param string $bodyPreview  First ~300 chars of the message body (plain text)
 * @param bool   $isReply      True if this is a reply to an existing thread
 */
function sendInboxMessageNotification($toEmail, $toName, $fromName, $subject, $bodyPreview, $isReply = false)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);

        $typeLabel = $isReply ? 'New Reply' : 'New Message';
        $mail->Subject = "[NROI] $typeLabel: $subject";

        // Truncate preview to 300 chars
        $preview = mb_strlen($bodyPreview) > 300
            ? mb_substr($bodyPreview, 0, 300) . '...'
            : $bodyPreview;

        $actionLine = $isReply
            ? 'You have received a reply to a message in your NROI Portal inbox.'
            : 'You have received a new message in your NROI Portal inbox.';

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #1e293b; text-align: center;'>$typeLabel</h2>
                <p>Hello <strong>$toName</strong>,</p>
                <p>$actionLine</p>
                <div style='background: #f8fafc; padding: 15px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #2563eb;'>
                    <p style='margin: 0 0 8px 0; font-size: 0.85rem; color: #64748b;'>
                        <strong>From:</strong> $fromName
                    </p>
                    <p style='margin: 0 0 8px 0; font-size: 0.85rem; color: #64748b;'>
                        <strong>Subject:</strong> $subject
                    </p>
                    <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 10px 0;'>
                    <p style='margin: 0; font-size: 0.9rem; color: #1e293b; line-height: 1.6;'>$preview</p>
                </div>
                <p style='text-align: center; margin: 25px 0;'>
                    <a href='https://pointscard.nroi.net/officer/notifications.php'
                       style='background-color: #2563eb; color: white; padding: 12px 28px;
                              text-decoration: none; border-radius: 6px; font-weight: bold;
                              display: inline-block;'>
                        View in NROI Portal
                    </a>
                </p>
                <p style='color: #64748b; font-size: 0.85rem; text-align: center;'>
                    Log in to the NROI Portal or open the NROI app to read and reply to this message.
                </p>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->AltBody = "$typeLabel from $fromName\n\nSubject: $subject\n\n$preview\n\nLog in to the NROI Portal to view and reply.";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Inbox Message Email could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

function sendEmailChangeRequest($toEmail, $fullName, $token)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $fullName);

        $mail->isHTML(true);
        $mail->Subject = 'Confirm Email Change Request - NROI Portal';

        $protocol = _nroi_is_https() ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'pointscard.nroi.net';

        $currentPath = $_SERVER['REQUEST_URI'] ?? '/';
        $baseDir = dirname($currentPath);
        if ($baseDir === '\\' || $baseDir === '/')
            $baseDir = '';
        if (strpos($baseDir, '/api') !== false)
            $baseDir = dirname($baseDir);

        $confirmLink = "$protocol://$host" . $baseDir . "/verify_email_change.php?token=$token";

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #1e293b; text-align: center;'>Email Change Request</h2>
                <p>Hello <strong>$fullName</strong>,</p>
                <p>We received a request to change the email address associated with your NROI Portal account. To proceed with this change, please click the button below:</p>
                <div style='text-align: center; margin: 30px 0;'>
                    <a href='$confirmLink' style='background-color: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; display: inline-block;'>Confirm & Change Email</a>
                </div>
                <p style='color: #64748b; font-size: 0.9rem;'>For security, this link will expire in 30 minutes. If you did not request this change, please ignore this email and ensure your account is secure.</p>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email Change Request could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

function sendEmailChangeNotification($toEmail, $fullName, $newEmail)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $fullName);

        $mail->isHTML(true);
        $mail->Subject = 'Email Address Successfully Updated - NROI Portal';

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #10b981; text-align: center;'>Email Updated Successfully</h2>
                <p>Hello <strong>$fullName</strong>,</p>
                <p>This email is to confirm that the email address for your NROI Portal account has been successfully updated to: <strong>$newEmail</strong>.</p>
                <p>From now on, please use this new email address to log in to your account.</p>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email Change Notification could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}

function sendAccountActivation($toEmail, $fullName, $username, $password, $token)
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'pointscard.nroi.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@pointscard.nroi.net';
        $mail->Password = 'ga)^Ld(z8GR1.-ME';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('no-reply@pointscard.nroi.net', 'NROI Portal');
        $mail->addAddress($toEmail, $fullName);

        $mail->isHTML(true);
        $mail->Subject = 'Account Activation - NROI Portal';

        $protocol = _nroi_is_https() ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'pointscard.nroi.net';

        // Build base URL
        $currentPath = $_SERVER['REQUEST_URI'] ?? '/';
        $baseDir = dirname($currentPath);
        if ($baseDir === '\\' || $baseDir === '/')
            $baseDir = '';
        if (strpos($baseDir, '/api') !== false)
            $baseDir = dirname($baseDir);

        $activateLink = "$protocol://$host" . $baseDir . "/api/activate_account.php?token=$token";

        $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='https://pointscard.nroi.net/assets/images/nroi_logo.png' alt='NROI Logo' style='height: 80px;'>
                </div>
                <h2 style='color: #1e293b; text-align: center;'>Account Activation Required</h2>
                <p>Hello,</p>
                <p>An account has been created for you on the NROI Portal. Below are your login credentials:</p>
                <div style='background: #f8fafc; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                    <p style='margin: 5px 0;'><strong>Username:</strong> $username</p>
                    <p style='margin: 5px 0;'><strong>Password:</strong> $password</p>
                </div>
                <p>To activate your account and begin using the portal, please click the button below:</p>
                <div style='text-align: center; margin: 30px 0;'>
                    <a href='$activateLink' style='background-color: #10b981; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; display: inline-block;'>Activate Account</a>
                </div>
                <p style='color: #64748b; font-size: 0.9rem; background: #fff7ed; padding: 12px; border-radius: 6px; border-left: 4px solid #f97316;'>
                    <strong>Important Reminder:</strong> This activation link can only be used <strong>once</strong>. Please ensure you provide all required and correct information (Name, Contact, Position, etc.) when completing your profile upon your first login.
                </p>
                <hr style='border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;'>
                <p style='color: #94a3b8; font-size: 0.8rem; text-align: center;'>National Range Officers Institute</p>
            </div>
        ";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Account Activation Email could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
?>