<?php
/**
 * Integrated Mail System for ZForex Trading Platform
 * Contains all 22 email templates with automatic triggering
 */

// Load PHPMailer via Composer autoloader
if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
    if (file_exists(__DIR__ . '/vendor/autoload.php')) {
        require_once __DIR__ . '/vendor/autoload.php';
    } elseif (file_exists(__DIR__ . '/PHPMailer/src/PHPMailer.php')) {
        require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
        require_once __DIR__ . '/PHPMailer/src/SMTP.php';
        require_once __DIR__ . '/PHPMailer/src/Exception.php';
    } else {
        echo "PHPMailer not found. Please install PHPMailer in the mail_system folder.\n";
        return false;
    }
}

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

class IntegratedMailSystem {
    private $mailer;
    private $templates;
    private $logFile;

    public function __construct() {
        $this->setupMailer();
        $this->loadTemplates();
        $this->logFile = LOG_PATH . 'email.log';
        
        // Ensure log directory exists
        if (!file_exists(LOG_PATH)) {
            mkdir(LOG_PATH, 0755, true);
        }
    }

    /**
     * Setup PHPMailer with configuration
     */
    private function setupMailer() {
        $this->mailer = new PHPMailer(true);
        
        try {
            // SMTP Configuration
            $this->mailer->isSMTP();
            $this->mailer->Host = MAIL_HOST;
            $this->mailer->SMTPAuth = true;
            $this->mailer->Username = MAIL_USERNAME;
            $this->mailer->Password = MAIL_PASSWORD;
            
            // Set encryption properly based on the constant value
            if (defined('MAIL_ENCRYPTION')) {
                if (MAIL_ENCRYPTION === 'ssl' || MAIL_ENCRYPTION === 'tls') {
                    $this->mailer->SMTPSecure = MAIL_ENCRYPTION;
                } elseif (MAIL_ENCRYPTION === 'PHPMailer::ENCRYPTION_SMTPS') {
                    $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                } else {
                    // Default to ssl if not specified
                    $this->mailer->SMTPSecure = 'ssl';
                }
            } else {
                // Default to ssl if constant not defined
                $this->mailer->SMTPSecure = 'ssl';
            }
            
            $this->mailer->Port = MAIL_PORT;
            
            // Enable SMTP debugging for troubleshooting
            // $this->mailer->SMTPDebug = 2; // Uncomment for debugging
            // $this->mailer->Debugoutput = 'echo'; // Uncomment for debugging
            
            // Sender Information
            $this->mailer->setFrom(MAIL_FROM_EMAIL, MAIL_FROM_NAME);
            
            // Additional settings
            $this->mailer->isHTML(true);
            $this->mailer->CharSet = 'UTF-8';
            
        } catch (Exception $e) {
            $this->logError("Mailer setup failed: " . $e->getMessage());
        }
    }

    /**
     * Load all email templates
     */
    private function loadTemplates() {
        $this->templates = [
            // 1. User Registration & Verification
'register_verification' => [
    'subject' => 'Welcome to {{company_name}} - Verify your email',
    'header'  => 'Welcome to {{company_name}}!',
    'body'    => '
        Thank you for joining us! Please verify your email address to activate your account.<br><br>
        This code expires in {{expiry_time}}.<br><br>
        <strong>Login Email:</strong> {{user_email}}<br>
        <strong>Password:</strong> {{user_password}}<br><br>
        After verifying, you can log in and start using your account. If you did not create this account, you can safely ignore this email.
    ',
    'button_text' => 'Verify Email',
    'button_url'  => '{{verification_url}}'
],


            
            // 2. Post-Verification Credentials
            'after_verify_credentials' => [
                'subject' => 'Account verified - Your login credentials',
                'header' => 'Account Successfully Verified!',
                'body' => 'Your account is now active. Here are your login credentials:<br><br><strong>Email:</strong> {{email}}<br><strong>User ID:</strong> {{user_id}}<br><br>Keep these credentials secure.',
                'button_text' => 'Login Now',
                'button_url' => '{{login_url}}'
            ],
            
            // 3. Login Alert
            'login_alert' => [
                'subject' => 'New login to your {{company_name}} account',
                'header' => 'Security Alert',
                'body' => 'We detected a new login to your account:<br><br><strong>Time:</strong> {{login_time}}<br><strong>IP Address:</strong> {{ip_address}}<br><strong>Device:</strong> {{device}}<br><br>If this wasn\'t you, please secure your account immediately.',
                'button_text' => 'Secure Account',
                'button_url' => '{{security_url}}'
            ],
            
            // 4. Live Account Opened
          'open_live_account' => [
    'subject' => 'Live trading account created - {{account_id}}',
    'header'  => 'Your Live Account is Ready!',
    'body'    => '
        Congratulations! Your live trading account has been successfully created.<br><br>
        <strong>Account ID:</strong> {{account_id}}<br>
        <strong>Account Type:</strong> {{account_type}}<br>
        <strong>Currency:</strong> {{currency}}<br>
                <strong>Server: Majesty Fx Server</strong><br>

        <strong>Master (Trader) Password:</strong> {{master_password}}<br>
        <strong>Investor Password:</strong> {{investor_password}}
    ',
    'button_text' => 'Start Trading',
    'button_url'  => '{{trading_url}}'
],

            
            // 5. KYC Upload
            'kyc_upload' => [
                'subject' => 'KYC documents received - Under review',
                'header' => 'Documents Received',
                'body' => 'Thank you for submitting your KYC documents. Our team is reviewing them and will notify you within 24-48 hours.<br><br><strong>Reference ID:</strong> {{reference_id}}<br><strong>Documents:</strong> {{document_list}}',
                'button_text' => 'Check Status',
                'button_url' => '{{kyc_status_url}}'
            ],
            
            // 6. KYC Approved
            'kyc_approved' => [
                'subject' => 'KYC approved - Full access granted ðŸŽ‰',
                'header' => 'Verification Complete!',
                'body' => 'Congratulations! Your KYC verification is approved. You now have full access to deposits, withdrawals, and all trading features.<br><br><strong>Approved:</strong> {{approval_date}}<br><strong>Verification Level:</strong> {{verification_level}}',
                'button_text' => 'Access Account',
                'button_url' => '{{dashboard_url}}'
            ],
            
            // 7. Deposit Request Submitted
            'deposit_request_submitted' => [
                'subject' => 'Deposit request received - {{amount}} {{currency}}',
                'header' => 'Deposit Request Received',
                'body' => 'Your deposit request has been received and is being processed.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Method:</strong> {{payment_method}}<br><strong>Reference:</strong> {{transaction_ref}}<br><br>Processing time: {{processing_time}}',
                'button_text' => 'Track Deposit',
                'button_url' => '{{tracking_url}}'
            ],
            
            // 8. Deposit Approved
            'deposit_approved' => [
                'subject' => 'Deposit approved - {{amount}} {{currency}} credited',
                'header' => 'Deposit Successful!',
                'body' => 'Your deposit has been approved and credited to your account.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>New Balance:</strong> {{new_balance}} {{currency}}<br><strong>Transaction ID:</strong> {{transaction_id}}',
                'button_text' => 'View Balance',
                'button_url' => '{{account_url}}'
            ],
            
            // 9. Deposit Failed
            'deposit_failed' => [
                'subject' => 'Deposit declined - {{amount}} {{currency}}',
                'header' => 'Deposit Unsuccessful',
                'body' => 'Unfortunately, your deposit could not be processed.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Reason:</strong> {{failure_reason}}<br><strong>Reference:</strong> {{transaction_ref}}<br><br>Please contact support for assistance.',
                'button_text' => 'Contact Support',
                'button_url' => '{{support_url}}'
            ],
            
            // 10. Withdrawal OTP
            'otp_withdrawal' => [
                'subject' => 'Withdrawal OTP - {{otp_code}}',
                'header' => 'Secure Your Withdrawal',
                'body' => 'Use this OTP to confirm your withdrawal request:<br><br><strong>OTP Code:</strong> {{otp_code}}<br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Destination:</strong> {{destination}}<br><br>This code expires in {{otp_expiry}}.',
                'button_text' => 'Complete Withdrawal',
                'button_url' => '{{withdrawal_url}}'
            ],
            
            'password_reset_issued' => [
    'subject' => '{{company_name}} | Password Reset Request',
    'body' => '
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto;">
            <div style="background-color: #004aad; padding: 20px; border-radius: 10px 10px 0 0;">
                <h2 style="color: #ffffff; text-align: center;">Password Reset Request</h2>
            </div>

            <div style="padding: 25px; background: #ffffff; border: 1px solid #eee; border-top: none;">
                <p>Hi {{user_name}},</p>
                <p>We received a request to reset your password for your <b>{{company_name}}</b> account.</p>
                <p>Your new temporary password is:</p>

                <div style="text-align:center; margin: 20px 0;">
                    <span style="background-color: #f5f5f5; padding: 12px 20px; border-radius: 8px; font-size: 18px; font-weight: bold; letter-spacing: 1px; border: 1px solid #ddd;">
                        {{new_password}}
                    </span>
                </div>

                <p>Please use the above password to log in and update your password immediately for security reasons.</p>

                <div style="text-align:center; margin: 30px 0;">
                    <a href="{{login_url}}" 
                       style="background-color: #004aad; color: white; text-decoration: none; padding: 12px 25px; border-radius: 6px; font-weight: bold;">
                       Go to Login
                    </a>
                </div>

                <p>If you didn’t request this change, please contact our support team immediately at 
                   <a href="mailto:{{support_email}}">{{support_email}}</a>.
                </p>
                <p>Thank you,<br>The {{company_name}} Team</p>
            </div>

            <div style="background: #f5f5f5; text-align: center; padding: 15px; border-radius: 0 0 10px 10px; font-size: 13px; color: #666;">
                &copy; {{company_name}} | All rights reserved.
            </div>
        </div>
    ',
],

            
            // 11. Withdrawal Request Submitted
      'withdrawal_request_submitted' => [
    'subject' => 'Withdrawal request received - {{amount}} {{currency}}',
    'header'  => 'Withdrawal Request Received',
    'body'    => 'Your withdrawal request is being processed.<br><br>
                  <strong>Amount:</strong> {{amount}} {{currency}}<br>
                  <strong>Type:</strong> {{type}}<br> <!-- ✅ Added -->
                  <strong>Reference:</strong> {{request_id}}<br><br>
                  Expected processing time: {{processing_time}}',
    'button_text' => 'Track Request',
    'button_url'  => '{{tracking_url}}'
],

            // 12. Withdrawal Approved
            'withdrawal_approved' => [
                'subject' => 'Withdrawal approved - {{amount}} {{currency}}',
                'header' => 'Withdrawal Processed',
                'body' => 'Your withdrawal has been approved and processed.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Transaction ID:</strong> {{transaction_id}}<br><strong>Expected Arrival:</strong> {{expected_arrival}}<br><strong>Remaining Balance:</strong> {{remaining_balance}} {{currency}}',
                'button_text' => 'View Transaction',
                'button_url' => '{{transaction_url}}'
            ],
            
            // 13. Withdrawal Rejected
            'withdrawal_rejected' => [
                'subject' => 'Withdrawal request declined - {{amount}} {{currency}}',
                'header' => 'Withdrawal Unsuccessful',
                'body' => 'Your withdrawal request has been declined.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Reason:</strong> {{rejection_reason}}<br><strong>Reference:</strong> {{request_id}}<br><br>Please contact support for more information.',
                'button_text' => 'Contact Support',
                'button_url' => '{{support_url}}'
            ],
            
            // 14. IB Commission Withdrawal
            'ib_commission_withdrawal' => [
                'subject' => 'IB commission withdrawal - {{amount}} {{currency}}',
                'header' => 'Commission Withdrawal Request',
                'body' => 'Your IB commission withdrawal request has been submitted.<br><br><strong>Commission Amount:</strong> {{amount}} {{currency}}<br><strong>Period:</strong> {{commission_period}}<br><strong>Total Clients:</strong> {{client_count}}<br><br>Processing will begin within 24 hours.',
                'button_text' => 'View Commission',
                'button_url' => '{{commission_url}}'
            ],
            'forgot_password' => [
    'subject' => '{{company_name}} | Password Reset Request',
    'header' => 'Password Reset Request',
    'body' => '
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto;">
            <div style="background-color: #004aad; padding: 20px; border-radius: 10px 10px 0 0;">
                <h2 style="color: #ffffff; text-align: center;">Password Reset Request</h2>
            </div>
            <div style="padding: 25px; background: #ffffff; border: 1px solid #eee; border-top: none;">
                <p>Hi {{user_name}},</p>
                <p>We received a request to reset your password for your <b>{{company_name}}</b> account.</p>
                <p>Your new temporary password is:</p>
                <div style="text-align:center; margin: 20px 0;">
                    <span style="background-color: #f5f5f5; padding: 12px 20px; border-radius: 8px; font-size: 18px; font-weight: bold; letter-spacing: 1px; border: 1px solid #ddd;">
                        {{new_password}}
                    </span>
                </div>
                <p>Please use the above password to log in and update your password immediately for security reasons.</p>
                <div style="text-align:center; margin: 30px 0;">
                    <a href="{{login_url}}"
                       style="background-color: #004aad; color: white; text-decoration: none; padding: 12px 25px; border-radius: 6px; font-weight: bold;">
                       Go to Login
                    </a>
                </div>
                <p>If you didn’t request this change, please contact our support team immediately at
                   <a href="mailto:{{support_email}}">{{support_email}}</a>.
                </p>
                <p>Thank you,<br>The {{company_name}} Team</p>
            </div>
            <div style="background: #f5f5f5; text-align: center; padding: 15px; border-radius: 0 0 10px 10px; font-size: 13px; color: #666;">
                &copy; {{company_name}} | All rights reserved.
            </div>
        </div>
    '
],
            
            // 15. Referral Registration
            'referral_registration' => [
                'subject' => 'New referral signup - Earn commission!',
                'header' => 'New Referral Registered!',
                'body' => 'Great news! Someone joined using your referral link.<br><br><strong>New Client:</strong> {{referral_name}}<br><strong>Registration Date:</strong> {{registration_date}}<br><strong>Your Commission Rate:</strong> {{commission_rate}}%<br><br>Start earning when they begin trading!',
                'button_text' => 'View Referrals',
                'button_url' => '{{referral_url}}'
            ],
            
            // 16. Trade Opened
            'trade_opened' => [
                'subject' => 'Trade opened - {{symbol}} {{volume}} lots',
                'header' => 'New Trade Opened',
                'body' => 'A new trade has been opened on your account.<br><br><strong>Symbol:</strong> {{symbol}}<br><strong>Type:</strong> {{trade_type}}<br><strong>Volume:</strong> {{volume}} lots<br><strong>Open Price:</strong> {{open_price}}<br><strong>Time:</strong> {{open_time}}',
                'button_text' => 'View Trade',
                'button_url' => '{{trade_url}}'
            ],
            
            // 17. Trade Closed
            'trade_closed' => [
                'subject' => 'Trade closed - {{symbol}} P&L: {{profit_loss}}',
                'header' => 'Trade Closed',
                'body' => 'Your trade has been closed.<br><br><strong>Symbol:</strong> {{symbol}}<br><strong>Volume:</strong> {{volume}} lots<br><strong>Open Price:</strong> {{open_price}}<br><strong>Close Price:</strong> {{close_price}}<br><strong>Profit/Loss:</strong> {{profit_loss}} {{currency}}<br><strong>Duration:</strong> {{trade_duration}}',
                'button_text' => 'View History',
                'button_url' => '{{history_url}}'
            ],
            
            // 18. Daily Trade Summary
            'daily_trade_summary' => [
                'subject' => 'Daily trading summary - {{date}}',
                'header' => 'Your Trading Summary',
                'body' => 'Here\'s your trading activity for {{date}}:<br><br><strong>Total Trades:</strong> {{total_trades}}<br><strong>Winning Trades:</strong> {{winning_trades}}<br><strong>Losing Trades:</strong> {{losing_trades}}<br><strong>Net P&L:</strong> {{net_pnl}} {{currency}}<br><strong>Account Balance:</strong> {{account_balance}} {{currency}}',
                'button_text' => 'View Details',
                'button_url' => '{{summary_url}}'
            ],
            
            // 19. Password Reset
            'password_reset' => [
                'subject' => 'Password reset request for your account',
                'header' => 'Reset Your Password',
                'body' => 'We received a request to reset your password. Use the link below to create a new password.<br><br><strong>Reset Code:</strong> {{reset_code}}<br><br>This link expires in {{expiry_time}}. If you didn\'t request this, please ignore this email.',
                'button_text' => 'Reset Password',
                'button_url' => '{{reset_url}}'
            ],
            
            // 20. Password Changed
            'password_changed' => [
                'subject' => 'Password changed successfully',
                'header' => 'Password Updated',
                'body' => 'Your account password has been successfully changed.<br><br><strong>Changed on:</strong> {{change_date}}<br><strong>IP Address:</strong> {{ip_address}}<br><br>If you didn\'t make this change, please contact support immediately.',
                'button_text' => 'Contact Support',
                'button_url' => '{{support_url}}'
            ],
            
            // 21. Profile Updated
            'profile_updated' => [
                'subject' => 'Profile information updated',
                'header' => 'Profile Updated',
                'body' => 'Your profile information has been successfully updated.<br><br><strong>Updated Fields:</strong> {{updated_fields}}<br><strong>Update Time:</strong> {{update_time}}<br><br>If you didn\'t make these changes, please contact support.',
                'button_text' => 'View Profile',
                'button_url' => '{{profile_url}}'
            ],
            
            // 22. Monthly Statement
            'monthly_statement' => [
                'subject' => 'Monthly account statement - {{month}} {{year}}',
                'header' => 'Monthly Statement',
                'body' => 'Your monthly trading statement is ready.<br><br><strong>Period:</strong> {{month}} {{year}}<br><strong>Total Trades:</strong> {{total_trades}}<br><strong>Net P&L:</strong> {{net_pnl}} {{currency}}<br><strong>Deposits:</strong> {{total_deposits}} {{currency}}<br><strong>Withdrawals:</strong> {{total_withdrawals}} {{currency}}<br><strong>Ending Balance:</strong> {{ending_balance}} {{currency}}',
                'button_text' => 'Download Statement',
                'button_url' => '{{statement_url}}'
            ],
            
            'password_reset_issued' => [
    'subject'     => 'Your new password',
    'header'      => 'Password Reset Successful',
    'body'        => 'We have generated a new password for your account.<br><br>
                      <strong>New Password:</strong> {{new_password}}<br><br>
                      For security, please log in and change this password immediately from your profile/settings.',
    'button_text' => 'Go to Login',
    'button_url'  => '{{login_url}}'
]

        ];
    }

    /**
     * Render template with variables
     */
    private function renderTemplate($template, $variables) {
        $rendered = $template;
        foreach ($variables as $key => $value) {
            $rendered = str_replace('{{' . $key . '}}', $value, $rendered);
        }
        return $rendered;
    }

    /**
     * Generate email HTML structure
     */
    private function getEmailHTML($header, $body, $buttonText = null, $buttonUrl = null) {
        $logoUrl = MAIL_LOGO_URL;
        $companyName = MAIL_COMPANY_NAME;
        $companyAddress = MAIL_COMPANY_ADDRESS;
        $supportEmail = MAIL_SUPPORT_EMAIL;
        $websiteUrl = MAIL_WEBSITE_URL;
        
        $buttonHtml = '';
        if ($buttonText && $buttonUrl) {
            $buttonHtml = "
                <div style='text-align: center; margin: 30px 0;'>
                    <a href='$buttonUrl' style='background-color: #007bff; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;'>$buttonText</a>
                </div>";
        }

        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>$header</title>
        </head>
        <body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;'>
            <div style='background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;'>
                <div style='text-align: center; margin-bottom: 20px;'>
                    <img src='$logoUrl' alt='$companyName' style='max-height: 60px;'>
                </div>
                <h1 style='color: #007bff; text-align: center; margin-bottom: 20px;'>$header</h1>
                <div style='background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);'>
                    $body
                    $buttonHtml
                </div>
                <div style='text-align: center; margin-top: 20px; font-size: 12px; color: #666;'>
                    <p>$companyName<br>$companyAddress</p>
                    <p>Need help? Contact us at <a href='mailto:$supportEmail'>$supportEmail</a></p>
                    <p><a href='$websiteUrl'>Visit our website</a> | <a href='$websiteUrl/unsubscribe'>Unsubscribe</a></p>
                </div>
            </div>
        </body>
        </html>";
    }
    
 


    /**
     * Send email with template
     */
    public function sendMail($email, $name, $templateKey, $variables = []) {
        if (!EMAIL_AUTOMATION_ENABLED) {
            return ['success' => false, 'message' => 'Email automation is disabled'];
        }

        if (!isset($this->templates[$templateKey])) {
            $this->logError("Template not found: $templateKey");
            return ['success' => false, 'message' => 'Template not found'];
        }

        $template = $this->templates[$templateKey];
        
        // Add default variables
        $defaultVariables = [
            'company_name' => MAIL_COMPANY_NAME,
            'support_email' => MAIL_SUPPORT_EMAIL,
            'website_url' => MAIL_WEBSITE_URL,
            'current_year' => date('Y'),
            'current_date' => date('F j, Y'),
            'current_time' => date('g:i A'),
            'user_name' => $name,
            'user_email' => $email
        ];
        
        $variables = array_merge($defaultVariables, $variables);

        try {
            // Clear previous recipients
            $this->mailer->clearAddresses();
            $this->mailer->clearAttachments();
            
            // Set recipient
            $this->mailer->addAddress($email, $name);
            
            // Render template
            $subject = $this->renderTemplate($template['subject'], $variables);
            $header = $this->renderTemplate($template['header'], $variables);
            $body = $this->renderTemplate($template['body'], $variables);
            $buttonText = isset($template['button_text']) ? $this->renderTemplate($template['button_text'], $variables) : null;
            $buttonUrl = isset($template['button_url']) ? $this->renderTemplate($template['button_url'], $variables) : null;
            
            // Set email content
            $this->mailer->Subject = $subject;
            $this->mailer->Body = $this->getEmailHTML($header, $body, $buttonText, $buttonUrl);
            
            // Send email
            $result = $this->mailer->send();
            
            if ($result) {
                $this->logSuccess("Email sent successfully to $email using template $templateKey");
                return ['success' => true, 'message' => 'Email sent successfully'];
            } else {
                $this->logError("Failed to send email to $email using template $templateKey");
                return ['success' => false, 'message' => 'Failed to send email'];
            }
            
        } catch (Exception $e) {
            $this->logError("Email sending exception: " . $e->getMessage());
            return ['success' => false, 'message' => 'Email sending failed: ' . $e->getMessage()];
        }
    }

    /**
     * Log success message
     */
    private function logSuccess($message) {
        if (EMAIL_LOG_ENABLED) {
            $timestamp = date('Y-m-d H:i:s');
            $logEntry = "[$timestamp] [SUCCESS] $message" . PHP_EOL;
            file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
        }
    }

    /**
     * Log error message
     */
    private function logError($message) {
        if (EMAIL_LOG_ENABLED) {
            $timestamp = date('Y-m-d H:i:s');
            $logEntry = "[$timestamp] [ERROR] $message" . PHP_EOL;
            file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
        }
        
        // Also log to PHP error log
        error_log("IntegratedMailSystem Error: $message");
    }

    // ================================
    // QUICK SEND METHODS FOR ALL TEMPLATES
    // ================================

// MailSystem.php (or wherever your mailer class is)
public function sendRegisterVerification(
    $email,
    $name,
    $verification_code,
    $expiry_time = '15 minutes',
    $plain_password = ''
) {
    return $this->sendMail($email, $name, 'register_verification', [
        'verification_code' => $verification_code,
        'expiry_time'       => $expiry_time,
        'verification_url'  => 'https://server.vistafxsolutions.com/verify_email.php?token=' . $verification_code,
        'user_email'        => $email,
        'user_password'     => $plain_password,
    ]);
}



    public function sendAfterVerifyCredentials($email, $name, $user_id) {
        return $this->sendMail($email, $name, 'after_verify_credentials', [
            'email' => $email,
            'user_id' => $user_id,
            'login_url' => APP_URL . '/login'
        ]);
    }

    public function sendLoginAlert($email, $name, $ip_address, $device = 'Unknown') {
        return $this->sendMail($email, $name, 'login_alert', [
            'login_time' => date('F j, Y g:i A'),
            'ip_address' => $ip_address,
            'device' => $device,
            'security_url' => APP_URL . '/security'
        ]);
    }

  public function sendLiveAccountOpened(
    $email,
    $name,
    $account_id,
    $account_type,
    $leverage,
    $currency = 'USD',
    $master_password = '',
    $investor_password = ''
) {
    return $this->sendMail($email, $name, 'open_live_account', [
        'account_id'       => $account_id,
        'account_type'     => $account_type,
        'leverage'         => $leverage,
        'currency'         => $currency,
        'master_password'  => $master_password,
        'investor_password'=> $investor_password,
        'trading_url'      => APP_URL . '/login'
    ]);
}


    public function sendKYCUpload($email, $name, $reference_id, $document_list = 'ID Document, Address Proof') {
        return $this->sendMail($email, $name, 'kyc_upload', [
            'reference_id' => $reference_id,
            'document_list' => $document_list,
            'kyc_status_url' => APP_URL . '/kyc-status'
        ]);
    }

    public function sendKYCApproved($email, $name, $verification_level = 'Full', $approval_date = null) {
        return $this->sendMail($email, $name, 'kyc_approved', [
            'approval_date' => $approval_date ?: date('F j, Y'),
            'verification_level' => $verification_level,
            'dashboard_url' => APP_URL . '/dashboard'
        ]);
    }

    public function sendDepositRequestSubmitted($email, $name, $amount, $currency, $payment_method, $transaction_ref) {
        return $this->sendMail($email, $name, 'deposit_request_submitted', [
            'amount' => number_format($amount, 2),
            'currency' => $currency,
            'payment_method' => $payment_method,
            'transaction_ref' => $transaction_ref,
            'processing_time' => '1-24 hours',
            'tracking_url' => APP_URL . '/deposits'
        ]);
    }
    public function sendForgotPassword($email, $name, $new_password) {
    return $this->sendMail($email, $name, 'forgot_password', [
        'new_password' => $new_password,
        'login_url' => 'https://user.qfx-markets.com/login', // direct client login
        'support_url' => (defined('APP_URL') ? APP_URL : '') . '/support'
    ]);
}
    

    public function sendDepositApproved($email, $name, $amount, $currency, $new_balance, $transaction_id) {
        return $this->sendMail($email, $name, 'deposit_approved', [
            'amount' => number_format($amount, 2),
            'currency' => $currency,
            'new_balance' => number_format($new_balance, 2),
            'transaction_id' => $transaction_id,
            'account_url' => APP_URL . '/account'
        ]);
    }

    public function sendDepositFailed($email, $name, $amount, $currency, $failure_reason, $transaction_ref) {
        return $this->sendMail($email, $name, 'deposit_failed', [
            'amount' => number_format($amount, 2),
            'currency' => $currency,
            'failure_reason' => $failure_reason,
            'transaction_ref' => $transaction_ref,
            'support_url' => APP_URL . '/support'
        ]);
    }

    public function sendWithdrawalOTP($email, $name, $otp_code, $amount, $currency, $destination, $otp_expiry = '10 minutes') {
        return $this->sendMail($email, $name, 'otp_withdrawal', [
            'otp_code' => $otp_code,
            'amount' => number_format($amount, 2),
            'currency' => $currency,
            'destination' => $destination,
            'otp_expiry' => $otp_expiry,
            'withdrawal_url' => APP_URL . '/withdrawal/confirm'
        ]);
    }
    
    public function sendPasswordResetIssued($email, $name, $new_password) {
    return $this->sendMail($email, $name, 'password_reset_issued', [
        'new_password' => $new_password,
        'login_url'    => 'https://user.qfx-markets.com/login', // direct client login
        'support_url'  => (defined('APP_URL') ? APP_URL : '') . '/support'
    ]);
}


   // Mailer class
public function sendWithdrawalRequestSubmitted(
    $email,
    $name,
    $amount,
    $currency,
    $withdrawal_method,
    $request_id,
    $type = '' // <-- added (optional)
) {
    return $this->sendMail($email, $name, 'withdrawal_request_submitted', [
        'amount'            => number_format($amount, 2),
        'currency'          => $currency,
        'withdrawal_method' => $withdrawal_method,
        'request_id'        => $request_id,
        'type'              => $type, // <-- include in template data
        'processing_time'   => WITHDRAWAL_PROCESSING_TIME,
        'tracking_url'      => APP_URL . '/withdrawals'
    ]);
}


    public function sendWithdrawalApproved($email, $name, $amount, $currency, $transaction_id, $expected_arrival, $remaining_balance) {
        return $this->sendMail($email, $name, 'withdrawal_approved', [
            'amount' => number_format($amount, 2),
            'currency' => $currency,
            'transaction_id' => $transaction_id,
            'expected_arrival' => $expected_arrival,
            'remaining_balance' => number_format($remaining_balance, 2),
            'transaction_url' => APP_URL . '/transactions'
        ]);
    }

    public function sendWithdrawalRejected($email, $name, $amount, $currency, $rejection_reason, $request_id) {
        return $this->sendMail($email, $name, 'withdrawal_rejected', [
            'amount' => number_format($amount, 2),
            'currency' => $currency,
            'rejection_reason' => $rejection_reason,
            'request_id' => $request_id,
            'support_url' => APP_URL . '/support'
        ]);
    }

    public function sendIBCommissionWithdrawal($email, $name, $amount, $currency, $commission_period, $client_count) {
        return $this->sendMail($email, $name, 'ib_commission_withdrawal', [
            'amount' => number_format($amount, 2),
            'currency' => $currency,
            'commission_period' => $commission_period,
            'client_count' => $client_count,
            'commission_url' => APP_URL . '/ib/commission'
        ]);
    }

    public function sendReferralRegistration($email, $name, $referral_name, $commission_rate) {
        return $this->sendMail($email, $name, 'referral_registration', [
            'referral_name' => $referral_name,
            'registration_date' => date('F j, Y'),
            'commission_rate' => $commission_rate,
            'referral_url' => APP_URL . '/referrals'
        ]);
    }

    public function sendTradeOpened($email, $name, $symbol, $trade_type, $volume, $open_price) {
        return $this->sendMail($email, $name, 'trade_opened', [
            'symbol' => $symbol,
            'trade_type' => $trade_type,
            'volume' => $volume,
            'open_price' => $open_price,
            'open_time' => date('F j, Y g:i A'),
            'trade_url' => APP_URL . '/trading'
        ]);
    }

    public function sendTradeClosed($email, $name, $symbol, $volume, $open_price, $close_price, $profit_loss, $currency, $trade_duration) {
        return $this->sendMail($email, $name, 'trade_closed', [
            'symbol' => $symbol,
            'volume' => $volume,
            'open_price' => $open_price,
            'close_price' => $close_price,
            'profit_loss' => number_format($profit_loss, 2),
            'currency' => $currency,
            'trade_duration' => $trade_duration,
            'history_url' => APP_URL . '/history'
        ]);
    }

    public function sendDailyTradeSummary($email, $name, $date, $total_trades, $winning_trades, $losing_trades, $net_pnl, $currency, $account_balance) {
        return $this->sendMail($email, $name, 'daily_trade_summary', [
            'date' => $date,
            'total_trades' => $total_trades,
            'winning_trades' => $winning_trades,
            'losing_trades' => $losing_trades,
            'net_pnl' => number_format($net_pnl, 2),
            'currency' => $currency,
            'account_balance' => number_format($account_balance, 2),
            'summary_url' => APP_URL . '/reports'
        ]);
    }

    public function sendPasswordReset($email, $name, $reset_code, $expiry_time = '1 hour') {
        return $this->sendMail($email, $name, 'password_reset', [
            'reset_code' => $reset_code,
            'expiry_time' => $expiry_time,
            'reset_url' => APP_URL . '/reset-password?code=' . $reset_code
        ]);
    }

    public function sendPasswordChanged($email, $name, $ip_address) {
        return $this->sendMail($email, $name, 'password_changed', [
            'change_date' => date('F j, Y g:i A'),
            'ip_address' => $ip_address,
            'support_url' => APP_URL . '/support'
        ]);
    }

    public function sendProfileUpdated($email, $name, $updated_fields) {
        return $this->sendMail($email, $name, 'profile_updated', [
            'updated_fields' => $updated_fields,
            'update_time' => date('F j, Y g:i A'),
            'profile_url' => APP_URL . '/profile'
        ]);
    }

    public function sendMonthlyStatement($email, $name, $month, $year, $total_trades, $net_pnl, $currency, $total_deposits, $total_withdrawals, $ending_balance) {
        return $this->sendMail($email, $name, 'monthly_statement', [
            'month' => $month,
            'year' => $year,
            'total_trades' => $total_trades,
            'net_pnl' => number_format($net_pnl, 2),
            'currency' => $currency,
            'total_deposits' => number_format($total_deposits, 2),
            'total_withdrawals' => number_format($total_withdrawals, 2),
            'ending_balance' => number_format($ending_balance, 2),
            'statement_url' => APP_URL . '/statements'
        ]);
    }
}

// ================================
// GLOBAL MAIL FUNCTION
// ================================

/**
 * Global function to send emails easily
 */
function sendZForexMail($email, $name, $template, $variables = []) {
    static $mailSystem = null;
    
    if ($mailSystem === null) {
        $mailSystem = new IntegratedMailSystem();
    }
    
    return $mailSystem->sendMail($email, $name, $template, $variables);
}

/**
 * Get mail system instance
 */
function getMailSystem() {
    static $mailSystem = null;
    
    if ($mailSystem === null) {
        $mailSystem = new IntegratedMailSystem();
    }
    
    return $mailSystem;
}

?>