<?php
require_once 'config.php';

// Check if PHPMailer is available, if not provide installation instructions
if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
    // Try to include PHPMailer from common locations
    $phpmailer_paths = [
        __DIR__ . '/vendor/autoload.php',
        __DIR__ . '/phpmailer/autoload.php',
        __DIR__ . '/PHPMailer/src/PHPMailer.php'
    ];
    
    $phpmailer_found = false;
    foreach ($phpmailer_paths as $path) {
        if (file_exists($path)) {
            if (strpos($path, 'autoload.php') !== false) {
                require_once $path;
            } else {
                require_once $path;
                require_once dirname($path) . '/SMTP.php';
                require_once dirname($path) . '/Exception.php';
            }
            $phpmailer_found = true;
            break;
        }
    }
    
    if (!$phpmailer_found) {
        throw new Exception("PHPMailer not found. Please install it using: composer require phpmailer/phpmailer");
    }
}

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

class ZForexMailer {
    private $mailer;
    private $templates;
    
    public function __construct() {
        $this->mailer = new PHPMailer(true);
        $this->setupSMTP();
        $this->loadTemplates();
    }
    
    private function setupSMTP() {
        try {
            $this->mailer->isSMTP();
            $this->mailer->Host = MAIL_HOST;
            $this->mailer->SMTPAuth = true;
            $this->mailer->Username = MAIL_USERNAME;
            $this->mailer->Password = MAIL_PASSWORD;
            $this->mailer->SMTPSecure = MAIL_ENCRYPTION;
            $this->mailer->Port = MAIL_PORT;
            $this->mailer->setFrom(MAIL_FROM_EMAIL, MAIL_FROM_NAME);
            $this->mailer->isHTML(true);
        } catch (Exception $e) {
            error_log("SMTP Setup Error: " . $e->getMessage());
        }
    }
    
    private function loadTemplates() {
        $this->templates = [
            'register_verification' => [
                'subject' => 'Verify your email & activate your {{brand_name}} account',
                'header' => 'Welcome to {{brand_name}}!',
                'body' => 'Please verify your email to start trading with us. Click below to confirm your account.',
                'button_text' => 'Verify Email',
                'button_url' => '{{verification_url}}'
            ],
            'after_verify_credentials' => [
                'subject' => 'Your {{brand_name}} login credentials',
                'header' => 'Your account is ready',
                'body' => 'Use the credentials below to log in and start exploring your dashboard.<br><br><strong>Email:</strong> {{email}}<br><strong>Password:</strong> {{password}}',
                'button_text' => 'Login Now',
                'button_url' => '{{login_url}}'
            ],
            'login_alert' => [
                'subject' => 'Login Alert – {{brand_name}}',
                'header' => 'We noticed a login to your account',
                'body' => 'If this was not you, secure your account immediately.<br><br><strong>Time:</strong> {{login_time}}<br><strong>IP:</strong> {{ip_address}}<br><strong>Device:</strong> {{device}}',
                'button_text' => 'Secure Account',
                'button_url' => '{{security_url}}'
            ],
            'open_live_account' => [
                'subject' => 'Live trading account opened successfully',
                'header' => 'Your live account is ready',
                'body' => 'Start trading with Account ID: {{account_id}}.<br><br><strong>Account Type:</strong> {{account_type}}<br><strong>Leverage:</strong> {{leverage}}<br><strong>Currency:</strong> {{currency}}',
                'button_text' => 'Start Trading',
                'button_url' => '{{trading_url}}'
            ],
            'kyc_upload' => [
                'subject' => 'KYC submission received',
                'header' => 'Documents under review',
                'body' => 'We\'ll notify you once our compliance team approves them.<br><br><strong>Submitted:</strong> {{submission_date}}<br><strong>Reference:</strong> {{reference_id}}',
                'button_text' => 'Check Status',
                'button_url' => '{{kyc_status_url}}'
            ],
            'kyc_approved' => [
                'subject' => 'Your KYC is approved 🎉',
                'header' => 'Verification successful',
                'body' => 'You now have full access to deposits and withdrawals.<br><br><strong>Approved:</strong> {{approval_date}}<br><strong>Verification Level:</strong> {{verification_level}}',
                'button_text' => 'Make Deposit',
                'button_url' => '{{deposit_url}}'
            ],
            'deposit_request_submitted' => [
                'subject' => 'Deposit request received',
                'header' => 'We got your request',
                'body' => 'We\'ll process your deposit and notify you when approved.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Method:</strong> {{payment_method}}<br><strong>Reference:</strong> {{transaction_id}}',
                'button_text' => 'Track Status',
                'button_url' => '{{transaction_url}}'
            ],
            'deposit_approved' => [
                'subject' => 'Deposit approved – {{amount}} {{currency}} added',
                'header' => 'Funds credited',
                'body' => 'Your wallet balance is updated. Happy trading!<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>New Balance:</strong> {{new_balance}} {{currency}}<br><strong>Transaction ID:</strong> {{transaction_id}}',
                'button_text' => 'Start Trading',
                'button_url' => '{{trading_url}}'
            ],
            'otp_withdrawal' => [
                'subject' => 'Confirm withdrawal with OTP',
                'header' => 'Secure your withdrawal',
                'body' => 'Enter OTP {{otp_code}} (valid {{otp_expiry}}).<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Destination:</strong> {{destination}}',
                'button_text' => 'Complete Withdrawal',
                'button_url' => '{{withdrawal_url}}'
            ],
            'withdrawal_request_submitted' => [
                'subject' => 'Withdrawal request received',
                'header' => 'We\'re processing your withdrawal',
                'body' => 'Funds will be released once approved.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Method:</strong> {{payment_method}}<br><strong>Reference:</strong> {{transaction_id}}',
                'button_text' => 'Track Status',
                'button_url' => '{{transaction_url}}'
            ],
            'withdrawal_approved' => [
                'subject' => 'Withdrawal approved – {{amount}} {{currency}}',
                'header' => 'Funds released',
                'body' => 'Your withdrawal is successfully processed.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Transaction ID:</strong> {{transaction_id}}<br><strong>Expected Arrival:</strong> {{expected_arrival}}',
                'button_text' => 'View Transaction',
                'button_url' => '{{transaction_url}}'
            ],
            'ib_commission_withdrawal' => [
                'subject' => 'IB commission withdrawal request',
                'header' => 'Commission withdrawal submitted',
                'body' => 'Use OTP to confirm and track status in your dashboard.<br><br><strong>Commission Amount:</strong> {{amount}} {{currency}}<br><strong>Period:</strong> {{commission_period}}<br><strong>OTP:</strong> {{otp_code}}',
                'button_text' => 'Confirm Withdrawal',
                'button_url' => '{{withdrawal_url}}'
            ],
            'referral_registration' => [
                'subject' => 'New referral joined via your link',
                'header' => 'Congrats!',
                'body' => '{{child_name}} joined under your referral code.<br><br><strong>Referral Code:</strong> {{referral_code}}<br><strong>Commission Rate:</strong> {{commission_rate}}%<br><strong>Joined:</strong> {{join_date}}',
                'button_text' => 'View Referrals',
                'button_url' => '{{referral_url}}'
            ],
            'trade_open' => [
                'subject' => 'Trade opened: {{trade_symbol}}',
                'header' => 'New trade placed',
                'body' => '{{trade_side}} {{trade_volume}} lots at {{price}}.<br><br><strong>Order ID:</strong> {{order_id}}<br><strong>Stop Loss:</strong> {{stop_loss}}<br><strong>Take Profit:</strong> {{take_profit}}',
                'button_text' => 'View Trade',
                'button_url' => '{{trading_url}}'
            ],
            'trade_close' => [
                'subject' => 'Trade closed: {{trade_symbol}}',
                'header' => 'Your trade has closed',
                'body' => 'Order {{order_id}} closed with {{amount}} {{currency}} P/L.<br><br><strong>Open Price:</strong> {{open_price}}<br><strong>Close Price:</strong> {{close_price}}<br><strong>Duration:</strong> {{duration}}',
                'button_text' => 'View History',
                'button_url' => '{{history_url}}'
            ],
            'daily_trade_summary' => [
                'subject' => 'Your 24h trading summary',
                'header' => 'Summary of your trading activity',
                'body' => 'Trades: {{trades_count}}, Net P/L: {{amount}} {{currency}}.<br><br><strong>Winning Trades:</strong> {{winning_trades}}<br><strong>Losing Trades:</strong> {{losing_trades}}<br><strong>Win Rate:</strong> {{win_rate}}%',
                'button_text' => 'View Details',
                'button_url' => '{{dashboard_url}}'
            ],
            'password_reset' => [
                'subject' => 'Reset your password',
                'header' => 'Password reset requested',
                'body' => 'Click the button below to reset your password.<br><br><strong>Request Time:</strong> {{request_time}}<br><strong>IP Address:</strong> {{ip_address}}',
                'button_text' => 'Reset Password',
                'button_url' => '{{reset_url}}'
            ],
            'password_changed' => [
                'subject' => 'Your password has been changed',
                'header' => 'Password updated',
                'body' => 'If this wasn\'t you, secure your account immediately.<br><br><strong>Changed:</strong> {{change_time}}<br><strong>IP Address:</strong> {{ip_address}}',
                'button_text' => 'Secure Account',
                'button_url' => '{{security_url}}'
            ],
            'profile_updated' => [
                'subject' => 'Profile updated successfully',
                'header' => 'Contact details updated',
                'body' => 'We\'ve updated your profile information.<br><br><strong>Updated Fields:</strong> {{updated_fields}}<br><strong>Update Time:</strong> {{update_time}}',
                'button_text' => 'View Profile',
                'button_url' => '{{profile_url}}'
            ],
            'deposit_failed' => [
                'subject' => 'Deposit declined – {{amount}} {{currency}}',
                'header' => 'Deposit unsuccessful',
                'body' => 'Reason: {{reason}}.<br><br><strong>Transaction ID:</strong> {{transaction_id}}<br><strong>Payment Method:</strong> {{payment_method}}<br><strong>Support:</strong> Contact us for assistance',
                'button_text' => 'Contact Support',
                'button_url' => '{{support_url}}'
            ],
            'withdrawal_rejected' => [
                'subject' => 'Withdrawal request declined',
                'header' => 'Withdrawal unsuccessful',
                'body' => 'Reason: {{reason}}.<br><br><strong>Amount:</strong> {{amount}} {{currency}}<br><strong>Transaction ID:</strong> {{transaction_id}}<br><strong>Support:</strong> Contact us for assistance',
                'button_text' => 'Contact Support',
                'button_url' => '{{support_url}}'
            ],
            'monthly_statement' => [
                'subject' => 'Your monthly statement ({{statement_period}})',
                'header' => 'Monthly report ready',
                'body' => 'Click below to view and download your detailed statement.<br><br><strong>Period:</strong> {{statement_period}}<br><strong>Total Trades:</strong> {{total_trades}}<br><strong>Net P/L:</strong> {{net_pnl}} {{currency}}',
                'button_text' => 'Download Statement',
                'button_url' => '{{statement_url}}'
            ]
        ];
    }
    
    private function renderTemplate($template_key, $variables = []) {
        if (!isset($this->templates[$template_key])) {
            throw new Exception("Template '$template_key' not found");
        }
        
        $template = $this->templates[$template_key];
        
        // Add brand name to variables if not provided
        if (!isset($variables['brand_name'])) {
            $variables['brand_name'] = BRAND_NAME;
        }
        
        // Replace variables in template
        foreach ($template as $key => $value) {
            foreach ($variables as $var_key => $var_value) {
                $template[$key] = str_replace('{{' . $var_key . '}}', $var_value, $template[$key]);
            }
        }
        
        return $template;
    }
    
    private function getEmailHTML($template) {
        // Use online logo URL for better performance and reliability
        $logo_url = 'https://ecotradefx.com/lib/logo.png';
        
        $html = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>' . $template['subject'] . '</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f4f4f4; }
                .container { max-width: 600px; margin: 0 auto; background-color: #ffffff; }
                .header { background-color: #1a73e8; color: white; padding: 30px; text-align: center; }
                .header img { max-width: 150px; height: auto; margin-bottom: 15px; display: block; margin-left: auto; margin-right: auto; }
                .header h1 { margin: 0; font-size: 24px; }
                .content { padding: 30px; }
                .content h2 { color: #333; margin-top: 0; }
                .content p { color: #666; line-height: 1.6; }
                .button { display: inline-block; background-color: #1a73e8; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; margin: 20px 0; }
                .button:hover { background-color: #1557b0; }
                .footer { background-color: #f8f9fa; padding: 20px; text-align: center; color: #666; font-size: 12px; }
                .footer a { color: #1a73e8; text-decoration: none; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <img src="' . $logo_url . '" alt="' . BRAND_NAME . ' Logo" />
                    <h1>' . $template['header'] . '</h1>
                </div>
                <div class="content">
                    <p>' . $template['body'] . '</p>';
        
        if (isset($template['button_text']) && isset($template['button_url'])) {
            $html .= '<p><a href="' . $template['button_url'] . '" class="button">' . $template['button_text'] . '</a></p>';
        }
        
        $html .= '
                </div>
                <div class="footer">
                    <p>&copy; ' . date('Y') . ' ' . BRAND_NAME . '. All rights reserved.</p>
                    <p><a href="#">Unsubscribe</a> | <a href="#">Privacy Policy</a> | <a href="#">Contact Support</a></p>
                </div>
            </div>
        </body>
        </html>';
        
        return $html;
    }
    
    public function sendMail($to_email, $to_name, $template_key, $variables = []) {
        try {
            $template = $this->renderTemplate($template_key, $variables);
            
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($to_email, $to_name);
            
            $this->mailer->Subject = $template['subject'];
            $this->mailer->Body = $this->getEmailHTML($template);
            $this->mailer->AltBody = strip_tags($template['body']);
            
            $result = $this->mailer->send();
            
            // Log successful email
            error_log("Email sent successfully to $to_email - Template: $template_key");
            
            return [
                'success' => true,
                'message' => 'Email sent successfully'
            ];
            
        } catch (Exception $e) {
            error_log("Email sending failed: " . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Email sending failed: ' . $e->getMessage()
            ];
        }
    }
    
    // Quick send methods for common emails
    public function sendRegisterVerification($email, $name, $verification_url) {
        return $this->sendMail($email, $name, 'register_verification', [
            'verification_url' => $verification_url
        ]);
    }
    
    public function sendLoginCredentials($email, $name, $password, $login_url) {
        return $this->sendMail($email, $name, 'after_verify_credentials', [
            'email' => $email,
            'password' => $password,
            'login_url' => $login_url
        ]);
    }
    
    public function sendLoginAlert($email, $name, $login_time, $ip_address, $device) {
        return $this->sendMail($email, $name, 'login_alert', [
            'login_time' => $login_time,
            'ip_address' => $ip_address,
            'device' => $device,
            'security_url' => 'https://yoursite.com/security'
        ]);
    }
    
    public function sendLiveAccountOpened($email, $name, $account_id, $account_type, $leverage, $currency) {
        return $this->sendMail($email, $name, 'open_live_account', [
            'account_id' => $account_id,
            'account_type' => $account_type,
            'leverage' => $leverage,
            'currency' => $currency,
            'trading_url' => 'https://yoursite.com/trading'
        ]);
    }
    
    public function sendKYCUpload($email, $name, $reference_id) {
        return $this->sendMail($email, $name, 'kyc_upload', [
            'submission_date' => date('Y-m-d H:i:s'),
            'reference_id' => $reference_id,
            'kyc_status_url' => 'https://yoursite.com/kyc-status'
        ]);
    }
    
    public function sendKYCApproved($email, $name, $verification_level = 'Full') {
        return $this->sendMail($email, $name, 'kyc_approved', [
            'approval_date' => date('Y-m-d H:i:s'),
            'verification_level' => $verification_level,
            'deposit_url' => 'https://yoursite.com/deposit'
        ]);
    }
    
    public function sendDepositRequest($email, $name, $amount, $currency, $payment_method, $transaction_id) {
        return $this->sendMail($email, $name, 'deposit_request_submitted', [
            'amount' => $amount,
            'currency' => $currency,
            'payment_method' => $payment_method,
            'transaction_id' => $transaction_id,
            'transaction_url' => 'https://yoursite.com/transactions/' . $transaction_id
        ]);
    }
    
    public function sendDepositApproved($email, $name, $amount, $currency, $new_balance, $transaction_id) {
        return $this->sendMail($email, $name, 'deposit_approved', [
            'amount' => $amount,
            'currency' => $currency,
            'new_balance' => $new_balance,
            'transaction_id' => $transaction_id,
            'trading_url' => 'https://yoursite.com/trading'
        ]);
    }
    
    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' => $amount,
            'currency' => $currency,
            'destination' => $destination,
            'otp_expiry' => $otp_expiry,
            'withdrawal_url' => 'https://yoursite.com/withdrawal'
        ]);
    }
    
    public function sendPasswordReset($email, $name, $reset_url, $ip_address) {
        return $this->sendMail($email, $name, 'password_reset', [
            'reset_url' => $reset_url,
            'request_time' => date('Y-m-d H:i:s'),
            'ip_address' => $ip_address
        ]);
    }
    
    // Add more quick send methods as needed...
}

// Global function for easy access
function sendZForexMail($to_email, $to_name, $template_key, $variables = []) {
    $mailer = new ZForexMailer();
    return $mailer->sendMail($to_email, $to_name, $template_key, $variables);
}

?>