<?php
/**
 * Email Templates
 * 
 * This file contains functions for generating and sending various email templates
 * used throughout the banking application.
 */

// Include the SMTP mailer if it exists
if (file_exists(__DIR__ . '/smtp_mailer.php')) {
    require_once __DIR__ . '/smtp_mailer.php';
}

/**
 * User Registration Email Template
 * 
 * Generates a professional HTML email for user registration confirmation
 * with a design that matches your banking application's aesthetic.
 * 
 * @param string $userName User's full name
 * @param string $accountNumber User's account number
 * @param string $email User's email address
 * @param string $verificationLink Email verification link
 * @return string HTML email content
 */
function generateRegistrationEmail($userName, $accountNumber, $email, $verificationLink) {
    // Bank branding variables - you can define these in your config file
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://yourdomain.com/assets/images/logo.png';
    $primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
    $secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
    $successColor = defined('BANK_SUCCESS_COLOR') ? BANK_SUCCESS_COLOR : '#059669';
    $currentYear = date('Y');
    
    // Email content
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to $bankName</title>
    <style>
        /* Base styles */
        body {
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        
        /* Container */
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .email-header {
            background: linear-gradient(135deg, $primaryColor, $secondaryColor);
            padding: 30px 20px;
            text-align: center;
            color: white;
        }
        
        .email-header img {
            max-width: 180px;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* Body */
        .email-body {
            padding: 30px;
        }
        
        /* Success Icon */
        .success-icon {
            width: 80px;
            height: 80px;
            background: $successColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            color: white;
            font-size: 40px;
        }
        
        /* Account Number Box */
        .account-number {
            background: #f8fafc;
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
            font-size: 18px;
            font-weight: 600;
            color: $secondaryColor;
            text-align: center;
        }
        
        /* Button */
        .button {
            display: inline-block;
            background: $primaryColor;
            color: white;
            text-decoration: none;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 500;
            margin: 20px 0;
            text-align: center;
        }
        
        /* Footer */
        .email-footer {
            background-color: #f8fafc;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Typography */
        h1, h2, h3, h4 {
            color: #1e293b;
            margin-top: 0;
        }
        
        h2 {
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        p {
            margin-bottom: 15px;
        }
        
        .text-muted {
            color: #64748b;
        }
        
        .text-center {
            text-align: center;
        }
        
        /* Security Notice */
        .security-notice {
            background-color: #fffbeb;
            border-left: 4px solid #f59e0b;
            padding: 15px;
            margin: 20px 0;
        }
        
        /* Steps */
        .steps {
            margin: 25px 0;
        }
        
        .step {
            display: flex;
            margin-bottom: 15px;
        }
        
        .step-number {
            width: 30px;
            height: 30px;
            background: $primaryColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            margin-right: 15px;
            flex-shrink: 0;
        }
        
        .step-content {
            flex: 1;
        }
        
        /* Responsive */
        @media only screen and (max-width: 600px) {
            .email-container {
                width: 100%;
                border-radius: 0;
            }
            
            .email-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
            <h1>Welcome to $bankName!</h1>
        </div>
        
        <div class="email-body">
            <div class="success-icon">✓</div>
            
            <h2 class="text-center">Registration Successful!</h2>
            <p class="text-center">Thank you for choosing $bankName. Your account has been created successfully.</p>
            
            <div class="account-number">
                Account Number: $accountNumber
            </div>
            
            <p>Dear $userName,</p>
            
            <p>We're delighted to welcome you to the $bankName family. Your new banking account has been created and is ready for activation.</p>
            
            <div class="security-notice">
                <strong>Important:</strong> For security reasons, please verify your email address by clicking the button below before accessing your account.
            </div>
            
            <div class="text-center">
                <a href="$verificationLink" class="button">Verify Email Address</a>
            </div>
            
            <h3>Next Steps:</h3>
            <div class="steps">
                <div class="step">
                    <div class="step-number">1</div>
                    <div class="step-content">
                        <strong>Verify your email</strong> by clicking the button above
                    </div>
                </div>
                <div class="step">
                    <div class="step-number">2</div>
                    <div class="step-content">
                        <strong>Log in to your account</strong> using your credentials
                    </div>
                </div>
                <div class="step">
                    <div class="step-number">3</div>
                    <div class="step-content">
                        <strong>Complete your profile</strong> and set up security preferences
                    </div>
                </div>
                <div class="step">
                    <div class="step-number">4</div>
                    <div class="step-content">
                        <strong>Start banking</strong> with our full range of services
                    </div>
                </div>
            </div>
            
            <p>If you have any questions or need assistance, our customer support team is available 24/7 to help you.</p>
            
            <p>Thank you for choosing $bankName for your financial needs.</p>
            
            <p>Best regards,<br>The $bankName Team</p>
        </div>
        
        <div class="email-footer">
            <p>This email was sent to $email</p>
            <p>Please do not reply to this email. This mailbox is not monitored.</p>
            <p>For assistance, please contact our customer support at info@firstnationalbankinc.com</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    return $emailBody;
}

/**
 * Password Reset Email Template
 * 
 * Generates an HTML email for password reset requests
 * 
 * @param string $userName User's full name
 * @param string $resetLink Password reset link
 * @param string $email User's email address
 * @return string HTML email content
 */
function generatePasswordResetEmail($userName, $resetLink, $email) {
    // Bank branding variables
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://yourdomain.com/assets/images/logo.png';
    $primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
    $secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
    $warningColor = defined('BANK_WARNING_COLOR') ? BANK_WARNING_COLOR : '#f59e0b';
    $currentYear = date('Y');
    
    // Email content
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Reset Request</title>
    <style>
        /* Base styles */
        body {
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        
        /* Container */
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .email-header {
            background: linear-gradient(135deg, $primaryColor, $secondaryColor);
            padding: 30px 20px;
            text-align: center;
            color: white;
        }
        
        .email-header img {
            max-width: 180px;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* Body */
        .email-body {
            padding: 30px;
        }
        
        /* Warning Icon */
        .warning-icon {
            width: 80px;
            height: 80px;
            background: $warningColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            color: white;
            font-size: 40px;
        }
        
        /* Button */
        .button {
            display: inline-block;
            background: $primaryColor;
            color: white;
            text-decoration: none;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 500;
            margin: 20px 0;
            text-align: center;
        }
        
        /* Footer */
        .email-footer {
            background-color: #f8fafc;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Typography */
        h1, h2, h3, h4 {
            color: #1e293b;
            margin-top: 0;
        }
        
        h2 {
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        p {
            margin-bottom: 15px;
        }
        
        .text-muted {
            color: #64748b;
        }
        
        .text-center {
            text-align: center;
        }
        
        /* Security Notice */
        .security-notice {
            background-color: #fffbeb;
            border-left: 4px solid #f59e0b;
            padding: 15px;
            margin: 20px 0;
        }
        
        /* Responsive */
        @media only screen and (max-width: 600px) {
            .email-container {
                width: 100%;
                border-radius: 0;
            }
            
            .email-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
            <h1>Password Reset Request</h1>
        </div>
        
        <div class="email-body">
            <div class="warning-icon">!</div>
            
            <h2 class="text-center">Reset Your Password</h2>
            
            <p>Dear $userName,</p>
            
            <p>We received a request to reset the password for your account. If you made this request, please click the button below to reset your password:</p>
            
            <div class="text-center">
                <a href="$resetLink" class="button">Reset Password</a>
            </div>
            
            <div class="security-notice">
                <strong>Important:</strong> If you didn't request a password reset, please ignore this email or contact our support team immediately. Your account security is important to us.
            </div>
            
            <p>This password reset link will expire in 1 hour for security reasons.</p>
            
            <p>If you're having trouble clicking the button, copy and paste the URL below into your web browser:</p>
            
            <p style="word-break: break-all; background: #f8fafc; padding: 10px; border-radius: 5px; font-size: 12px;">
                $resetLink
            </p>
            
            <p>If you have any questions or need assistance, our customer support team is available 24/7 to help you.</p>
            
            <p>Best regards,<br>The $bankName Team</p>
        </div>
        
        <div class="email-footer">
            <p>This email was sent to $email</p>
            <p>Please do not reply to this email. This mailbox is not monitored.</p>
            <p>For assistance, please contact our customer support at info@firstnationalbankinc.com</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    return $emailBody;
}

/**
 * Transaction Notification Email Template
 * 
 * Generates an HTML email for transaction notifications
 * 
 * @param string $userName User's full name
 * @param string $transactionType Type of transaction (deposit, withdrawal, transfer)
 * @param float $amount Transaction amount
 * @param string $currency Currency code
 * @param string $accountNumber Account number
 * @param string $transactionId Transaction ID
 * @param string $date Transaction date
 * @param string $email User's email address
 * @return string HTML email content
 */
function generateTransactionEmail($userName, $transactionType, $amount, $currency, $accountNumber, $transactionId, $date, $email) {
    // Bank branding variables
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://yourdomain.com/assets/images/logo.png';
    $primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
    $secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
    $currentYear = date('Y');
    
    // Set color based on transaction type
    $transactionColor = '#2563eb'; // Default blue
    $transactionIcon = '↔️'; // Default icon
    
    if ($transactionType == 'deposit') {
        $transactionColor = '#059669'; // Green
        $transactionIcon = '⬇️';
        $transactionTitle = 'Deposit Confirmation';
    } elseif ($transactionType == 'withdrawal') {
        $transactionColor = '#dc2626'; // Red
        $transactionIcon = '⬆️';
        $transactionTitle = 'Withdrawal Confirmation';
    } elseif ($transactionType == 'transfer') {
        $transactionColor = '#7c3aed'; // Purple
        $transactionIcon = '↔️';
        $transactionTitle = 'Transfer Confirmation';
    } else {
        $transactionTitle = 'Transaction Confirmation';
    }
    
    // Format amount with 2 decimal places
    $formattedAmount = number_format($amount, 2);
    
    // Email content
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>$transactionTitle</title>
    <style>
        /* Base styles */
        body {
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        
        /* Container */
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .email-header {
            background: linear-gradient(135deg, $primaryColor, $secondaryColor);
            padding: 30px 20px;
            text-align: center;
            color: white;
        }
        
        .email-header img {
            max-width: 180px;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* Body */
        .email-body {
            padding: 30px;
        }
        
        /* Transaction Icon */
        .transaction-icon {
            width: 80px;
            height: 80px;
            background: $transactionColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            color: white;
            font-size: 40px;
        }
        
        /* Transaction Details */
        .transaction-details {
            background: #f8fafc;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .transaction-amount {
            font-size: 24px;
            font-weight: 600;
            color: $transactionColor;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            color: #64748b;
            font-weight: 500;
        }
        
        .detail-value {
            font-weight: 600;
            text-align: right;
        }
        
        /* Button */
        .button {
            display: inline-block;
            background: $primaryColor;
            color: white;
            text-decoration: none;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 500;
            margin: 20px 0;
            text-align: center;
        }
        
        /* Footer */
        .email-footer {
            background-color: #f8fafc;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Typography */
        h1, h2, h3, h4 {
            color: #1e293b;
            margin-top: 0;
        }
        
        h2 {
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        p {
            margin-bottom: 15px;
        }
        
        .text-muted {
            color: #64748b;
        }
        
        .text-center {
            text-align: center;
        }
        
        /* Responsive */
        @media only screen and (max-width: 600px) {
            .email-container {
                width: 100%;
                border-radius: 0;
            }
            
            .email-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
            <h1>$transactionTitle</h1>
        </div>
        
        <div class="email-body">
            <div class="transaction-icon">$transactionIcon</div>
            
            <h2 class="text-center">Transaction Successful</h2>
            
            <div class="transaction-amount">
                $currency $formattedAmount
            </div>
            
            <p>Dear $userName,</p>
            
            <p>We're confirming that the following transaction has been completed successfully:</p>
            
            <div class="transaction-details">
                <div class="detail-row">
                    <div class="detail-label">Transaction Type</div>
                    <div class="detail-value">" . ucfirst($transactionType) . "</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Amount</div>
                    <div class="detail-value">$currency $formattedAmount</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Account Number</div>
                    <div class="detail-value">$accountNumber</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Transaction ID</div>
                    <div class="detail-value">$transactionId</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Date & Time</div>
                    <div class="detail-value">$date</div>
                </div>
            </div>
            
            <div class="text-center">
                <a href="#" class="button">View Transaction Details</a>
            </div>
            
            <p>If you did not authorize this transaction or notice any discrepancies, please contact our customer support team immediately.</p>
            
            <p>Thank you for banking with us.</p>
            
            <p>Best regards,<br>The $bankName Team</p>
        </div>
        
        <div class="email-footer">
            <p>This email was sent to $email</p>
            <p>Please do not reply to this email. This mailbox is not monitored.</p>
            <p>For assistance, please contact our customer support at info@firstnationalbankinc.com</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    return $emailBody;
}

/**
 * Function to send the registration confirmation email
 * 
 * @param string $to Recipient email address
 * @param string $userName User's full name
 * @param string $accountNumber User's account number
 * @param string $verificationCode Email verification code
 * @return bool Success status
 */
function sendRegistrationEmail($to, $userName, $accountNumber, $verificationCode) {
    // Generate verification link
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $verificationLink = "$protocol://$host/verify.php?email=" . urlencode($to) . "&code=" . $verificationCode;
    
    // Log the verification link for debugging
    error_log("Verification link generated: $verificationLink");
    
    // Generate email content
    $emailBody = generateRegistrationEmail($userName, $accountNumber, $to, $verificationLink);
    
    // Email subject
    $subject = "Welcome to " . (defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated');
    
    // Send the email using the best available method
    return sendEmailByBestMethod($to, $subject, $emailBody);
}

/**
 * Function to send a password reset email
 * 
 * @param string $to Recipient email address
 * @param string $userName User's full name
 * @param string $token Password reset token
 * @return bool Success status
 */
function sendPasswordResetEmail($to, $userName, $token) {
    // Generate reset link with robust URL construction
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    
    // Use the direct_reset.php file
    $resetLink = "$protocol://$host/direct_reset.php?email=" . urlencode($to) . "&token=" . urlencode($token);
    
    // Log the reset link for debugging
    error_log("Password reset link generated: $resetLink");
    
    // Generate email content
    $emailBody = generatePasswordResetEmail($userName, $resetLink, $to);
    
    // Email subject
    $subject = "Password Reset Request - " . (defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated');
    
    // Send the email using the best available method
    return sendEmailByBestMethod($to, $subject, $emailBody);
}


/**
 * Function to send a transaction notification email
 * 
 * @param string $to Recipient email address
 * @param string $userName User's full name
 * @param string $transactionType Type of transaction
 * @param float $amount Transaction amount
 * @param string $currency Currency code
 * @param string $accountNumber Account number
 * @param string $transactionId Transaction ID
 * @return bool Success status
 */
function sendTransactionEmail($to, $userName, $transactionType, $amount, $currency, $accountNumber, $transactionId) {
    // Format date
    $date = date('F j, Y, g:i a');
    
    // Generate email content
    $emailBody = generateTransactionEmail($userName, $transactionType, $amount, $currency, $accountNumber, $transactionId, $date, $to);
    
    // Email subject
    $transactionTitle = ucfirst($transactionType) . " Confirmation";
    $subject = $transactionTitle . " - " . (defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated');
    
    // Send the email using the best available method
    return sendEmailByBestMethod($to, $subject, $emailBody);
}

/**
 * Ticket Creation Confirmation Email Template
 * 
 * Generates an HTML email for ticket creation confirmation
 * 
 * @param string $userName User's full name
 * @param int $ticketId Ticket ID
 * @param string $subject Ticket subject
 * @param string $message Ticket message
 * @param string $email User's email address
 * @return string HTML email content
 */
function generateTicketCreationEmail($userName, $ticketId, $subject, $message, $email) {
    // Bank branding variables
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://yourdomain.com/assets/images/logo.png';
    $primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
    $secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
    $infoColor = defined('BANK_INFO_COLOR') ? BANK_INFO_COLOR : '#3b82f6';
    $currentYear = date('Y');
    
    // Format the current date
    $currentDate = date('F j, Y, g:i a');
    
    // Format the message with proper HTML escaping
    $formattedMessage = nl2br(htmlspecialchars($message));
    
    // Generate ticket URL
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'yourbank.com';
    $ticketUrl = "$protocol://$host/customer/ticket_details.php?id=$ticketId";
    
    // Email content
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Support Ticket Created</title>
    <style>
        /* Base styles */
        body {
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        
        /* Container */
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .email-header {
            background: linear-gradient(135deg, $primaryColor, $secondaryColor);
            padding: 30px 20px;
            text-align: center;
            color: white;
        }
        
        .email-header img {
            max-width: 180px;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* Body */
        .email-body {
            padding: 30px;
        }
        
        /* Support Icon */
        .support-icon {
            width: 80px;
            height: 80px;
            background: $infoColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            color: white;
            font-size: 40px;
        }
        
        /* Ticket Details */
        .ticket-details {
            background: #f8fafc;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            color: #64748b;
            font-weight: 500;
        }
        
        .detail-value {
            font-weight: 600;
            text-align: right;
        }
        
        /* Message Box */
        .message-box {
            background-color: #f8fafc;
            padding: 15px;
            border-left: 4px solid $infoColor;
            margin: 15px 0;
            border-radius: 0 5px 5px 0;
        }
        
        /* Button */
        .button {
            display: inline-block;
            background: $primaryColor;
            color: white;
            text-decoration: none;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 500;
            margin: 20px 0;
            text-align: center;
        }
        
        /* Footer */
        .email-footer {
            background-color: #f8fafc;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Typography */
        h1, h2, h3, h4 {
            color: #1e293b;
            margin-top: 0;
        }
        
        h2 {
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        p {
            margin-bottom: 15px;
        }
        
        .text-muted {
            color: #64748b;
        }
        
        .text-center {
            text-align: center;
        }
        
        /* Responsive */
        @media only screen and (max-width: 600px) {
            .email-container {
                width: 100%;
                border-radius: 0;
            }
            
            .email-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
            <h1>Support Ticket Created</h1>
        </div>
        
        <div class="email-body">
            <div class="support-icon">?</div>
            
            <h2 class="text-center">Ticket Confirmation</h2>
            
            <p>Dear $userName,</p>
            
            <p>Thank you for contacting our support team. Your ticket has been created successfully and will be addressed by our team as soon as possible.</p>
            
            <div class="ticket-details">
                <div class="detail-row">
                    <div class="detail-label">Ticket ID: </div>
                    <div class="detail-value">#$ticketId</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Subject: </div>
                    <div class="detail-value">$subject</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Status: </div>
                    <div class="detail-value">Open</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Date Created: </div>
                    <div class="detail-value">$currentDate</div>
                </div>
            </div>
            
            <h3>Your Message:</h3>
            <div class="message-box">
                $formattedMessage
            </div>
            
            <div class="text-center">
                <a href="$ticketUrl" class="button">View Ticket</a>
            </div>
            
            <p>Our support team will review your ticket and respond as soon as possible. You will receive an email notification when there's an update to your ticket.</p>
            
            <p>If you have any additional information to add, please log in to your account and update your ticket.</p>
            
            <p>Thank you for your patience.</p>
            
            <p>Best regards,<br>The $bankName Support Team</p>
        </div>
        
        <div class="email-footer">
            <p>This email was sent to $email</p>
            <p>Please do not reply to this email. This mailbox is not monitored.</p>
            <p>For assistance, please contact our customer support at info@firstnationalbankinc.com</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    return $emailBody;
}

function sendWireTransferEmail($to, $userName, $amount, $currency, $fee, $recipientName, $bankName, $swiftCode, $accountNumber, $transactionId, $description, $country) {
    error_log("sendWireTransferEmail called with email: " . $to);
    
    try {
        // Get country name from code
        $countries = [
            'US' => 'United States', 'GB' => 'United Kingdom', 'CA' => 'Canada', 
            'AU' => 'Australia', 'DE' => 'Germany', 'FR' => 'France', 
            'JP' => 'Japan', 'CN' => 'China', 'IN' => 'India', 
            'SG' => 'Singapore', 'CH' => 'Switzerland', 'ES' => 'Spain', 
            'IT' => 'Italy', 'NL' => 'Netherlands', 'BR' => 'Brazil', 
            'MX' => 'Mexico', 'ZA' => 'South Africa', 'NG' => 'Nigeria', 
            'KE' => 'Kenya', 'AE' => 'United Arab Emirates'
        ];
        $countryName = $countries[$country] ?? $country;
        
        // Format amount and fee
        $formattedAmount = number_format($amount, 2);
        $formattedFee = number_format($fee, 2);
        $formattedTotal = number_format($amount + $fee, 2);
        
        // Generate transaction URL
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
        $transactionUrl = "$protocol://$host/customer/wire-transfer-success.php";
        
        // Email subject
        $subject = "International Wire Transfer Initiated - $currency $formattedAmount";
        
        // Email body
        $body = generateWireTransferEmailBody(
            $userName,
            $amount,
            $currency,
            $fee,
            $recipientName,
            $bankName,
            $swiftCode,
            $accountNumber,
            $transactionId,
            $description,
            $countryName,
            $transactionUrl
        );
        
        error_log("Email subject: " . $subject);
        error_log("Email body length: " . strlen($body));
        
        // Check if sendEmail function exists
        if (!function_exists('sendEmail')) {
            error_log("sendEmail function not found, using mail() function directly");
            
            // Use PHP's mail function directly
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: noreply@yourbank.com" . "\r\n";
            
            $result = mail($to, $subject, $body, $headers);
            
            // ADD THIS CODE HERE
            if ($result) {
                error_log("Email sent successfully to $to");
            } else {
                error_log("Email failed to send to $to");
                error_log("PHP mail() error info: " . (error_get_last()['message'] ?? 'No error info'));
            }
            return $result;
            
        } else {
            // Use existing sendEmail function
            error_log("Using existing sendEmail function");
            $result = sendEmail($to, $subject, $body);
            
            // AND ALSO ADD THIS CODE HERE
            if ($result) {
                error_log("Email sent successfully to $to");
            } else {
                error_log("Email failed to send to $to");
                error_log("PHP mail() error info: " . (error_get_last()['message'] ?? 'No error info'));
            }
            return $result;
        }
        
    } catch (Exception $e) {
        error_log("Error in sendWireTransferEmail: " . $e->getMessage());
        return false;
    }
}


/**
 * Generate wire transfer email body
 */
function generateWireTransferEmailBody($userName, $amount, $currency, $fee, $recipientName, $bankName, $swiftCode, $accountNumber, $transactionId, $description, $country, $transactionUrl) {
    $formattedAmount = number_format($amount, 2);
    $formattedFee = number_format($fee, 2);
    $formattedTotal = number_format($amount + $fee, 2);
    
    // Mask account number for security
    $maskedAccount = maskAccountNumber($accountNumber);
    
    $emailBody = '
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Wire Transfer Initiated</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; }
            .header { background-color: #0047cc; color: white; padding: 20px; text-align: center; }
            .content { padding: 20px; }
            .footer { background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666; }
            .transaction-details { background-color: #f9f9f9; padding: 15px; border-radius: 5px; margin: 20px 0; }
            .detail-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #eee; }
            .detail-row:last-child { border-bottom: none; }
            .detail-label { font-weight: bold; }
            .btn { display: inline-block; background-color: #0047cc; color: white; text-decoration: none; padding: 10px 20px; border-radius: 5px; margin-top: 20px; }
            .warning { color: #cc4400; font-size: 12px; margin-top: 20px; }
        </style>
    </head>
    <body>
        <div class="header">
            <h2>International Wire Transfer Initiated</h2>
        </div>
        <div class="content">
            <p>Dear ' . htmlspecialchars($userName) . ',</p>
            
            <p>Your international wire transfer has been initiated and is now being processed. Please allow 1-5 business days for the funds to reach the recipient\'s account.</p>
            
            <div class="transaction-details">
                <div class="detail-row">
                    <span class="detail-label">Transaction ID:</span>
                    <span>' . htmlspecialchars($transactionId) . '</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Amount:</span>
                    <span>' . htmlspecialchars($currency) . ' ' . htmlspecialchars($formattedAmount) . '</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Wire Transfer Fee:</span>
                    <span>' . htmlspecialchars($currency) . ' ' . htmlspecialchars($formattedFee) . '</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Total Debit:</span>
                    <span>' . htmlspecialchars($currency) . ' ' . htmlspecialchars($formattedTotal) . '</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Recipient:</span>
                    <span>' . htmlspecialchars($recipientName) . '</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Bank:</span>
                    <span>' . htmlspecialchars($bankName) . '</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">SWIFT/BIC:</span>
                    <span>' . htmlspecialchars($swiftCode) . '</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Account Number:</span>
                    <span>' . htmlspecialchars($maskedAccount) . '</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Country:</span>
                    <span>' . htmlspecialchars($country) . '</span>
                </div>
                ' . (!empty($description) ? '
                <div class="detail-row">
                    <span class="detail-label">Description:</span>
                    <span>' . htmlspecialchars($description) . '</span>
                </div>' : '') . '
            </div>
            
            <p>You can view the details of this transaction by clicking the button below:</p>
            
            <div style="text-align: center;">
                <a href="' . $transactionUrl . '" class="btn">View Transaction Details</a>
            </div>
            
            <p class="warning">Note: International wire transfers typically take 1-5 business days to complete. If the funds have not been received after 5 business days, please contact our customer support.</p>
        </div>
        <div class="footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>© ' . date('Y') . ' Your Bank. All rights reserved.</p>
        </div>
    <!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
    </html>';
    
    return $emailBody;
}

/**
 * Mask account number for security
 */
function maskAccountNumber($accountNumber) {
    $length = strlen($accountNumber);
    
    if ($length <= 4) {
        return $accountNumber;
    }
    
    $visibleChars = 4;
    $maskedPortion = str_repeat('*', $length - $visibleChars);
    $visiblePortion = substr($accountNumber, -$visibleChars);
    
    return $maskedPortion . $visiblePortion;
}

/**
 * Basic sendEmail function if it doesn't exist
 */
if (!function_exists('sendEmail')) {
    function sendEmail($to, $subject, $body) {
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: noreply@yourbank.com" . "\r\n";
        
        return mail($to, $subject, $body, $headers);
    }
}


/**
 * Transfer Notification Email Template
 * 
 * Generates an HTML email for transfer notifications
 * 
 * @param string $userName Sender's full name
 * @param string $recipientName Recipient's full name
 * @param string $amount Transfer amount
 * @param string $currency Currency code
 * @param string $accountNumber Recipient's account number
 * @param string $transactionId Transaction ID
 * @param string $description Transfer description
 * @param string $email User's email address
 * @return string HTML email content
 */
function generateTransferEmail($userName, $recipientName, $amount, $currency, $accountNumber, $transactionId, $description, $email) {
    // Bank branding variables
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://yourdomain.com/assets/images/logo.png';
    $primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
    $secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
    $successColor = defined('BANK_SUCCESS_COLOR') ? BANK_SUCCESS_COLOR : '#059669';
    $currentYear = date('Y');
    
    // Format the current date
    $currentDate = date('F j, Y, g:i a');
    
    // Format the amount with 2 decimal places
    $formattedAmount = number_format($amount, 2);
    
    // Format the description (if provided)
    $descriptionHtml = '';
    if (!empty($description)) {
        $descriptionHtml = '<div class="detail-row">
                <div class="detail-label">Description</div>
                <div class="detail-value">' . htmlspecialchars($description) . '</div>
            </div>';
    }
    
    // Generate transaction URL
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'yourbank.com';
    $transactionUrl = "$protocol://$host/customer/transfer_success.php?id=$transactionId";
    
    // Email content
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transfer Confirmation</title>
    <style>
        /* Base styles */
        body {
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        
        /* Container */
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .email-header {
            background: linear-gradient(135deg, $primaryColor, $secondaryColor);
            padding: 30px 20px;
            text-align: center;
            color: white;
        }
        
        .email-header img {
            max-width: 180px;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* Body */
        .email-body {
            padding: 30px;
        }
        
        /* Success Icon */
        .success-icon {
            width: 80px;
            height: 80px;
            background: $successColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            color: white;
            font-size: 40px;
        }
        
        /* Amount Display */
        .amount-display {
            text-align: center;
            margin: 20px 0;
        }
        
        .amount-label {
            font-size: 16px;
            color: #64748b;
            margin-bottom: 5px;
        }
        
        .amount-value {
            font-size: 32px;
            font-weight: 700;
            color: $successColor;
        }
        
        /* Transaction Details */
        .transaction-details {
            background: #f8fafc;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            color: #64748b;
            font-weight: 500;
        }
        
        .detail-value {
            font-weight: 600;
            text-align: right;
        }
        
        /* Button */
        .button {
            display: inline-block;
            background: $primaryColor;
            color: white;
            text-decoration: none;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 500;
            margin: 20px 0;
            text-align: center;
        }
        
        /* Footer */
        .email-footer {
            background-color: #f8fafc;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Typography */
        h1, h2, h3, h4 {
            color: #1e293b;
            margin-top: 0;
        }
        
        h2 {
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        p {
            margin-bottom: 15px;
        }
        
        .text-muted {
            color: #64748b;
        }
        
        .text-center {
            text-align: center;
        }
        
        /* Responsive */
        @media only screen and (max-width: 600px) {
            .email-container {
                width: 100%;
                border-radius: 0;
            }
            
            .email-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
            <h1>Transfer Confirmation</h1>
        </div>
        
        <div class="email-body">
            <div class="success-icon">✓</div>
            
            <h2 class="text-center">Transfer Successful</h2>
            
            <div class="amount-display">
                <div class="amount-label">Amount Transferred</div>
                <div class="amount-value">$currency $formattedAmount</div>
            </div>
            
            <p>Dear $userName,</p>
            
            <p>Your money transfer has been completed successfully. Here are the details of your transaction:</p>
            
            <div class="transaction-details">
                <div class="detail-row">
                    <div class="detail-label">Transaction ID</div>
                    <div class="detail-value">$transactionId</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Date & Time</div>
                    <div class="detail-value">$currentDate</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Recipient</div>
                    <div class="detail-value">$recipientName</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Account Number</div>
                    <div class="detail-value">$accountNumber</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Amount</div>
                    <div class="detail-value">$currency $formattedAmount</div>
                </div>
                $descriptionHtml
            </div>
            
            <div class="text-center">
                <a href="$transactionUrl" class="button">View Transaction Details</a>
            </div>
            
            <p>If you did not authorize this transaction or notice any discrepancies, please contact our customer support team immediately.</p>
            
            <p>Thank you for banking with us.</p>
            
            <p>Best regards,<br>The $bankName Team</p>
        </div>
        
        <div class="email-footer">
            <p>This email was sent to $email</p>
            <p>Please do not reply to this email. This mailbox is not monitored.</p>
            <p>For assistance, please contact our customer support at info@firstnationalbankinc.com</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    return $emailBody;
}

/**
 * Function to send transfer notification email
 * 
 * @param string $to Recipient email address
 * @param string $userName Sender's full name
 * @param string $recipientName Recipient's full name
 * @param float $amount Transfer amount
 * @param string $currency Currency code
 * @param string $accountNumber Recipient's account number
 * @param string $transactionId Transaction ID
 * @param string $description Transfer description
 * @return bool Success status
 */
function sendTransferEmail($to, $userName, $recipientName, $amount, $currency, $accountNumber, $transactionId, $description) {
    // Generate email content
    $emailBody = generateTransferEmail($userName, $recipientName, $amount, $currency, $accountNumber, $transactionId, $description, $to);
    
    // Email subject
    $formattedAmount = number_format($amount, 2);
    $emailSubject = "Transfer Confirmation: $currency $formattedAmount - " . (defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated');
    
    // Send the email using the best available method
    return sendEmailByBestMethod($to, $emailSubject, $emailBody);
}

/**
 * Ticket Reply Notification Email Template
 * 
 * Generates an HTML email for ticket reply notifications
 * 
 * @param string $userName User's full name
 * @param int $ticketId Ticket ID
 * @param string $subject Ticket subject
 * @param string $message Reply message
 * @param string $adminName Admin/staff name who replied
 * @param string $email User's email address
 * @return string HTML email content
 */
function generateTicketReplyEmail($userName, $ticketId, $subject, $message, $adminName, $email) {
    // Bank branding variables
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://yourdomain.com/assets/images/logo.png';
    $primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
    $secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
    $infoColor = defined('BANK_INFO_COLOR') ? BANK_INFO_COLOR : '#3b82f6';
    $currentYear = date('Y');
    
    // Email content
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Reply to Your Support Ticket</title>
    <style>
        /* Base styles */
        body {
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        
        /* Container */
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .email-header {
            background: linear-gradient(135deg, $primaryColor, $secondaryColor);
            padding: 30px 20px;
            text-align: center;
            color: white;
        }
        
        .email-header img {
            max-width: 180px;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* Body */
        .email-body {
            padding: 30px;
        }
        
        /* Reply Icon */
        .reply-icon {
            width: 80px;
            height: 80px;
            background: $infoColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            color: white;
            font-size: 40px;
        }
        
        /* Ticket Details */
        .ticket-details {
            background: #f8fafc;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            color: #64748b;
            font-weight: 500;
        }
        
        .detail-value {
            font-weight: 600;
            text-align: right;
        }
        
        /* Message Box */
        .message-box {
            background-color: #f8fafc;
            padding: 15px;
            border-left: 4px solid $infoColor;
            margin: 15px 0;
            border-radius: 0 5px 5px 0;
        }
        
        .message-sender {
            font-weight: 600;
            margin-bottom: 10px;
            color: $primaryColor;
        }
        
        /* Button */
        .button {
            display: inline-block;
            background: $primaryColor;
            color: white;
            text-decoration: none;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 500;
            margin: 20px 0;
            text-align: center;
        }
        
        /* Footer */
        .email-footer {
            background-color: #f8fafc;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Typography */
        h1, h2, h3, h4 {
            color: #1e293b;
            margin-top: 0;
        }
        
        h2 {
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        p {
            margin-bottom: 15px;
        }
        
        .text-muted {
            color: #64748b;
        }
        
        .text-center {
            text-align: center;
        }
        
        /* Responsive */
        @media only screen and (max-width: 600px) {
            .email-container {
                width: 100%;
                border-radius: 0;
            }
            
            .email-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
            <h1>New Reply to Your Ticket</h1>
        </div>
        
        <div class="email-body">
            <div class="reply-icon">↩️</div>
            
            <h2 class="text-center">Support Team Response</h2>
            
            <p>Dear $userName,</p>
            
            <p>You have received a new reply to your support ticket.</p>
            
            <div class="ticket-details">
                <div class="detail-row">
                    <div class="detail-label">Ticket ID: </div>
                    <div class="detail-value">#$ticketId</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Subject: </div>
                    <div class="detail-value">$subject</div>
                </div>
                <div class="detail-row">
    <div class="detail-label">Reply Date: </div>
    <div class="detail-value">" . date('F j, Y, g:i a') . "</div>
</div>

            </div>
            
            <h3>Response from Support:</h3>
            <div class="message-box">
                <div class="message-sender">$adminName wrote:</div>
                " . nl2br(htmlspecialchars($message)) . "
            </div>
            
            <div class="text-center">
                <a href="#" class="button">View Full Conversation</a>
            </div>
            
            <p>If you have any additional questions or need further clarification, please log in to your account and reply to this ticket.</p>
            
            <p>Thank you for banking with us.</p>
            
            <p>Best regards,<br>The $bankName Support Team</p>
        </div>
        
        <div class="email-footer">
            <p>This email was sent to $email</p>
            <p>Please do not reply to this email. This mailbox is not monitored.</p>
            <p>For assistance, please contact our customer support at info@firstnationalbankinc.com</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    return $emailBody;
}

/**
 * Ticket Status Update Email Template
 * 
 * Generates an HTML email for ticket status updates
 * 
 * @param string $userName User's full name
 * @param int $ticketId Ticket ID
 * @param string $subject Ticket subject
 * @param string $newStatus New ticket status
 * @param string $email User's email address
 * @return string HTML email content
 */
function generateTicketStatusUpdateEmail($userName, $ticketId, $subject, $newStatus, $email) {
    // Bank branding variables
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://yourdomain.com/assets/images/logo.png';
    $primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
    $secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
    $infoColor = defined('BANK_INFO_COLOR') ? BANK_INFO_COLOR : '#3b82f6';
    $successColor = defined('BANK_SUCCESS_COLOR') ? BANK_SUCCESS_COLOR : '#10b981';
    $warningColor = defined('BANK_WARNING_COLOR') ? BANK_WARNING_COLOR : '#f59e0b';
    $currentYear = date('Y');
    
    // Set color based on status
    $statusColor = $infoColor; // Default blue for open
    $statusIcon = '🔄';
    $statusText = 'Open';
    
    if ($newStatus == 'in_progress') {
        $statusColor = $warningColor; // Orange for in progress
        $statusIcon = '⚙️';
        $statusText = 'In Progress';
    } elseif ($newStatus == 'closed') {
        $statusColor = $successColor; // Green for closed
        $statusIcon = '✅';
        $statusText = 'Closed';
    }
    
    // Email content
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ticket Status Updated</title>
    <style>
        /* Base styles */
        body {
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        
        /* Container */
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .email-header {
            background: linear-gradient(135deg, $primaryColor, $secondaryColor);
            padding: 30px 20px;
            text-align: center;
            color: white;
        }
        
        .email-header img {
            max-width: 180px;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* Body */
        .email-body {
            padding: 30px;
        }
        
        /* Status Icon */
        .status-icon {
            width: 80px;
            height: 80px;
            background: $statusColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            color: white;
            font-size: 40px;
        }
        
        /* Ticket Details */
        .ticket-details {
            background: #f8fafc;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            color: #64748b;
            font-weight: 500;
        }
        
        .detail-value {
            font-weight: 600;
            text-align: right;
        }
        
        /* Status Badge */
        .status-badge {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            background-color: $statusColor;
            color: white;
            font-weight: 600;
            font-size: 14px;
        }
        
        /* Button */
        .button {
            display: inline-block;
            background: $primaryColor;
            color: white;
            text-decoration: none;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 500;
            margin: 20px 0;
            text-align: center;
        }
        
        /* Footer */
        .email-footer {
            background-color: #f8fafc;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Typography */
        h1, h2, h3, h4 {
            color: #1e293b;
            margin-top: 0;
        }
        
        h2 {
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        p {
            margin-bottom: 15px;
        }
        
        .text-muted {
            color: #64748b;
        }
        
        .text-center {
            text-align: center;
        }
        
        /* Responsive */
        @media only screen and (max-width: 600px) {
            .email-container {
                width: 100%;
                border-radius: 0;
            }
            
            .email-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
            <h1>Ticket Status Updated</h1>
        </div>
        
        <div class="email-body">
            <div class="status-icon">$statusIcon</div>
            
            <h2 class="text-center">Status Changed to $statusText</h2>
            
            <p>Dear $userName,</p>
            
            <p>The status of your support ticket has been updated.</p>
            
            <div class="ticket-details">
                <div class="detail-row">
                    <div class="detail-label">Ticket ID: </div>
                    <div class="detail-value">#$ticketId</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Subject: </div>
                    <div class="detail-value">$subject</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">New Status: </div>
                    <div class="detail-value"><span class="status-badge">$statusText</span></div>
                </div>
              <div class="detail-row">
    <div class="detail-label">Reply Date</div>
    <div class="detail-value">" . date('F j, Y, g:i a') . "</div>
</div>

            </div>
HTML;

    // Add status-specific message
    if ($newStatus == 'closed') {
        $emailBody .= <<<HTML
            
            <p>Your ticket has been resolved and closed. If you're satisfied with the resolution, no further action is needed.</p>
            
            <p>If you need further assistance or if your issue hasn't been fully resolved, you can reopen the ticket by replying to it from your account dashboard.</p>
HTML;
    } elseif ($newStatus == 'in_progress') {
        $emailBody .= <<<HTML
            
            <p>Your ticket is now being actively worked on by our support team. We'll keep you updated on the progress.</p>
HTML;
    } else {
        $emailBody .= <<<HTML
            
            <p>Your ticket is now open and will be reviewed by our support team soon.</p>
HTML;
    }

    $emailBody .= <<<HTML
            
            <div class="text-center">
                <a href="#" class="button">View Ticket Details</a>
            </div>
            
            <p>Thank you for your patience.</p>
            
            <p>Best regards,<br>The $bankName Support Team</p>
        </div>
        
        <div class="email-footer">
            <p>This email was sent to $email</p>
            <p>Please do not reply to this email. This mailbox is not monitored.</p>
            <p>For assistance, please contact our customer support at info@firstnationalbankinc.com</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    return $emailBody;
}

/**
 * Function to send ticket creation confirmation email
 * 
 * @param string $to Recipient email address
 * @param string $userName User's full name
 * @param int $ticketId Ticket ID
 * @param string $subject Ticket subject
 * @param string $message Ticket message
 * @return bool Success status
 */
function sendTicketCreationEmail($to, $userName, $ticketId, $subject, $message) {
    // Generate email content
    $emailBody = generateTicketCreationEmail($userName, $ticketId, $subject, $message, $to);
    
    // Email subject
    $emailSubject = "Support Ticket #$ticketId Created - " . (defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated');
    
    // Send the email using the best available method
    return sendEmailByBestMethod($to, $emailSubject, $emailBody);
}

/**
 * Function to send ticket reply notification email
 * 
 * @param string $to Recipient email address
 * @param string $userName User's full name
 * @param int $ticketId Ticket ID
 * @param string $subject Ticket subject
 * @param string $message Reply message
 * @param string $adminName Admin/staff name who replied
 * @return bool Success status
 */
function sendTicketReplyEmail($to, $userName, $ticketId, $subject, $message, $adminName) {
    // Generate email content
    $emailBody = generateTicketReplyEmail($userName, $ticketId, $subject, $message, $adminName, $to);
    
    // Email subject
    $emailSubject = "New Reply to Ticket #$ticketId - " . (defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated');
    
    // Send the email using the best available method
    return sendEmailByBestMethod($to, $emailSubject, $emailBody);
}

/**
 * Function to send ticket status update email
 * 
 * @param string $to Recipient email address
 * @param string $userName User's full name
 * @param int $ticketId Ticket ID
 * @param string $subject Ticket subject
 * @param string $newStatus New ticket status
 * @return bool Success status
 */
function sendTicketStatusUpdateEmail($to, $userName, $ticketId, $subject, $newStatus) {
    // Generate email content
    $emailBody = generateTicketStatusUpdateEmail($userName, $ticketId, $subject, $newStatus, $to);
    
    // Email subject
    $statusText = ucfirst(str_replace('_', ' ', $newStatus));
    $emailSubject = "Ticket #$ticketId Status Updated to $statusText - " . (defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated');
    
    // Send the email using the best available method
    return sendEmailByBestMethod($to, $emailSubject, $emailBody);
}

/**
 * Helper function to send email using the best available method
 * 
 * @param string $to Recipient email address
 * @param string $subject Email subject
 * @param string $emailBody Email HTML content
 * @return bool Success status
 */
function sendEmailByBestMethod($to, $subject, $emailBody) {
    // Try to use SMTP mailer first (if available)
    if (function_exists('sendSMTPEmail')) {
        error_log("Using SMTP mailer to send email to: $to");
        return sendSMTPEmail($to, $subject, $emailBody);
    }
    
    // Fall back to the existing sendEmail function if available
    if (function_exists('sendEmail')) {
        error_log("Using sendEmail function to send email to: $to");
        return sendEmail($to, $subject, $emailBody);
    }
    
    // Last resort: use the built-in fallback
    error_log("Using fallback email method to send email to: $to");
    return sendEmailTemplate($to, $subject, $emailBody);
}

/**
 * PIN Reset Email Template
 * 
 * Generates an HTML email for PIN reset requests
 * 
 * @param string $userName User's full name
 * @param string $resetLink PIN reset link
 * @param string $email User's email address
 * @return string HTML email content
 */
function generatePinResetEmail($userName, $resetLink, $email) {
    // Bank branding variables
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://yourdomain.com/assets/images/logo.png';
    $primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
    $secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
    $warningColor = defined('BANK_WARNING_COLOR') ? BANK_WARNING_COLOR : '#f59e0b';
    $currentYear = date('Y');
    
    // Email content
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PIN Reset Request</title>
    <style>
        /* Base styles */
        body {
            font-family: 'Poppins', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
        }
        
        /* Container */
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        /* Header */
        .email-header {
            background: linear-gradient(135deg, $primaryColor, $secondaryColor);
            padding: 30px 20px;
            text-align: center;
            color: white;
        }
        
        .email-header img {
            max-width: 180px;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* Body */
        .email-body {
            padding: 30px;
        }
        
        /* Warning Icon */
        .warning-icon {
            width: 80px;
            height: 80px;
            background: $warningColor;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            color: white;
            font-size: 40px;
        }
        
        /* Button */
        .button {
            display: inline-block;
            background: $primaryColor;
            color: white;
            text-decoration: none;
            padding: 12px 25px;
            border-radius: 10px;
            font-weight: 500;
            margin: 20px 0;
            text-align: center;
        }
        
        /* Footer */
        .email-footer {
            background-color: #f8fafc;
            padding: 20px;
            text-align: center;
            font-size: 12px;
            color: #64748b;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Typography */
        h1, h2, h3, h4 {
            color: #1e293b;
            margin-top: 0;
        }
        
        h2 {
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        p {
            margin-bottom: 15px;
        }
        
        .text-muted {
            color: #64748b;
        }
        
        .text-center {
            text-align: center;
        }
        
        /* Security Notice */
        .security-notice {
            background-color: #fffbeb;
            border-left: 4px solid #f59e0b;
            padding: 15px;
            margin: 20px 0;
        }
        
        /* Responsive */
        @media only screen and (max-width: 600px) {
            .email-container {
                width: 100%;
                border-radius: 0;
            }
            
            .email-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
            <h1>PIN Reset Request</h1>
        </div>
        
        <div class="email-body">
            <div class="warning-icon">!</div>
            
            <h2 class="text-center">Reset Your PIN</h2>
            
            <p>Dear $userName,</p>
            
            <p>We received a request to reset the PIN for your account. If you made this request, please click the button below to reset your PIN:</p>
            
            <div class="text-center">
                <a href="$resetLink" class="button">Reset PIN</a>
            </div>
            
            <div class="security-notice">
                <strong>Important:</strong> If you didn't request a PIN reset, please ignore this email or contact our support team immediately. Your account security is important to us.
            </div>
            
            <p>This PIN reset link will expire in 1 hour for security reasons.</p>
            
            <p>If you're having trouble clicking the button, copy and paste the URL below into your web browser:</p>
            
            <p style="word-break: break-all; background: #f8fafc; padding: 10px; border-radius: 5px; font-size: 12px;">
                $resetLink
            </p>
            
            <p>If you have any questions or need assistance, our customer support team is available 24/7 to help you.</p>
            
            <p>Best regards,<br>The $bankName Team</p>
        </div>
        
        <div class="email-footer">
            <p>This email was sent to $email</p>
            <p>Please do not reply to this email. This mailbox is not monitored.</p>
            <p>For assistance, please contact our customer support at info@firstnationalbankinc.com</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    return $emailBody;
}

/**
 * Function to send a PIN reset email
 * 
 * @param string $to Recipient email address
 * @param string $userName User's full name
 * @param string $token Reset token
 * @return bool Success status
 */
function sendPinResetEmail($to, $userName, $token) {
    // Generate reset link with robust URL construction
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    
    // Use the direct_pin_reset.php file instead
    $resetLink = "$protocol://$host/direct_pin_reset.php?token=" . urlencode($token);
    
    // Log the reset link for debugging
    error_log("PIN reset link generated: $resetLink");
    
    // Generate email content
    $emailBody = generatePinResetEmail($userName, $resetLink, $to);
    
    // Email subject
    $subject = "PIN Reset Request - " . (defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated');
    
    // Send the email using the best available method
    return sendEmailByBestMethod($to, $subject, $emailBody);
}


/**
 * Fallback email sending function - only used if other methods aren't available
 * 
 * @param string $to Recipient email address
 * @param string $subject Email subject
 * @param string $emailBody Email HTML content
 * @return bool Success status
 */
if (!function_exists('sendEmailTemplate')) {
    function sendEmailTemplate($to, $subject, $emailBody) {
        // Email headers
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        
        // From header
        $bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
        $fromEmail = defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'noreply@yourdomain.com';
        $headers .= "From: $bankName <$fromEmail>" . "\r\n";
        
                // Log the email attempt
        error_log("Sending email to: $to, Subject: $subject");
        
        // Save a copy of the email to a file for debugging
        $logDir = "../logs";
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }
        
        $emailLog = fopen("$logDir/email_" . time() . "_" . md5($to . $subject) . ".html", "w");
        if ($emailLog) {
            fwrite($emailLog, "To: $to\nSubject: $subject\nHeaders: $headers\n\n$emailBody");
            fclose($emailLog);
            error_log("Email content saved to log file");
        }
        
        // Send the email
        try {
            $result = mail($to, $subject, $emailBody, $headers);
            error_log("Email result: " . ($result ? "Success" : "Failed"));
            return $result;
        } catch (Exception $e) {
            error_log("Error sending email: " . $e->getMessage());
            return false;
        }
    }
}
?>

