<?php
// admin/includes/emails/email_sender.php

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

class EmailSender {
    private $db;
    private $masterTemplate;
    private $bankName;
    private $bankLogo;
    private $bankAddress;
    private $socialLinks;
    private $siteUrl;
    
    public function __construct($db) {
        $this->db = $db;
        
        // Load the master template
        $this->masterTemplate = file_get_contents(__DIR__ . '/templates/master.html');
        
        // Get bank settings
        $this->bankName = defined('BANK_NAME') ? BANK_NAME : 'Ocean Bank Cooperation';
        $this->bankLogo = defined('BANK_LOGO') ? BANK_LOGO : BASE_URL . 'assets/img/logo.png';
        $this->bankAddress = defined('BANK_ADDRESS') ? BANK_ADDRESS : '1738 Morgan Street, Tallahassee, FL 32303';
        $this->siteUrl = BASE_URL;
        
        // Social media links
        $this->socialLinks = [
            'facebook' => [
                'url' => defined('FACEBOOK_URL') ? FACEBOOK_URL : '#',
                'icon' => defined('FACEBOOK_ICON') ? FACEBOOK_ICON : BASE_URL . 'assets/img/facebook-icon.png'
            ],
            'twitter' => [
                'url' => defined('TWITTER_URL') ? TWITTER_URL : '#',
                'icon' => defined('TWITTER_ICON') ? TWITTER_ICON : BASE_URL . 'assets/img/twitter-icon.png'
            ],
            'instagram' => [
                'url' => defined('INSTAGRAM_URL') ? INSTAGRAM_URL : '#',
                'icon' => defined('INSTAGRAM_ICON') ? INSTAGRAM_ICON : BASE_URL . 'assets/img/instagram-icon.png'
            ]
        ];
    }
    
    /**
     * Send an email using a specific template
     * 
     * @param string $to Recipient email
     * @param string $toName Recipient name
     * @param string $subject Email subject
     * @param string $templateName Template name without .html extension
     * @param array $data Data to replace in the template
     * @param array $ctaButton Optional CTA button [text, url]
     * @return bool True if email was sent successfully
     */
    public function sendTemplatedEmail($to, $toName, $subject, $templateName, $data = [], $ctaButton = null) {
        try {
            // Load the specific template
            $templatePath = __DIR__ . '/templates/' . $templateName . '.html';
            if (!file_exists($templatePath)) {
                throw new Exception("Email template not found: $templateName");
            }
            
            $templateContent = file_get_contents($templatePath);
            
            // Replace template variables with actual data
            foreach ($data as $key => $value) {
                $templateContent = str_replace('{{' . $key . '}}', $value, $templateContent);
            }
            
            // Prepare CTA button if provided
            $ctaButtonHtml = '';
            if ($ctaButton && isset($ctaButton['text']) && isset($ctaButton['url'])) {
                $ctaButtonHtml = '<a href="' . $ctaButton['url'] . '" class="cta-button">' . $ctaButton['text'] . '</a>';
            }
            
            // Replace CTA button placeholder
            $templateContent = str_replace('{{CTA_BUTTON_HTML}}', $ctaButtonHtml, $templateContent);
            
            // Prepare the complete email by inserting the specific template into the master template
            $emailBody = $this->masterTemplate;
            
            // Replace master template variables
            $replacements = [
                'EMAIL_SUBJECT' => $subject,
                'BANK_LOGO_URL' => $this->bankLogo,
                'BANK_NAME' => $this->bankName,
                'RECIPIENT_NAME' => $toName,
                'EMAIL_BODY' => $templateContent,
                'CTA_BUTTON' => $ctaButtonHtml,
                'FACEBOOK_URL' => $this->socialLinks['facebook']['url'],
                'FACEBOOK_ICON' => $this->socialLinks['facebook']['icon'],
                'TWITTER_URL' => $this->socialLinks['twitter']['url'],
                'TWITTER_ICON' => $this->socialLinks['twitter']['icon'],
                'INSTAGRAM_URL' => $this->socialLinks['instagram']['url'],
                'INSTAGRAM_ICON' => $this->socialLinks['instagram']['icon'],
                'CURRENT_YEAR' => date('Y'),
                'BANK_ADDRESS' => $this->bankAddress,
                'RECIPIENT_EMAIL' => $to
            ];
            
            foreach ($replacements as $key => $value) {
                $emailBody = str_replace('{{' . $key . '}}', $value, $emailBody);
            }
            
            // Send the email using the internal method
            return $this->sendMailInternal($to, $toName, $subject, $emailBody);
            
        } catch (Exception $e) {
            error_log("Email sending error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Send a user registration email
     * 
     * @param array $user User data including email, name, account_number, etc.
     * @return bool True if email was sent successfully
     */
    public function sendUserRegistrationEmail($user) {
        $loginUrl = $this->siteUrl . 'login.php';
        
        return $this->sendTemplatedEmail(
            $user['email'],
            $user['first_name'] . ' ' . $user['last_name'],
            'Your Account Has Been Created - ' . $this->bankName,
            'user_registration',
            [
                'BANK_NAME' => $this->bankName,
                'ACCOUNT_NUMBER' => $user['account_number'],
                'ACCOUNT_TYPE' => ucfirst($user['account_type']),
                'USERNAME' => $user['username']
            ],
            [
                'text' => 'Login to Your Account',
                'url' => $loginUrl
            ]
        );
    }
    
    /**
     * Send a transaction notification email
     * 
     * @param array $user User data including email, name
     * @param array $transaction Transaction details
     * @param string $currentBalance Current account balance after transaction
     * @return bool True if email was sent successfully
     */
    public function sendTransactionNotificationEmail($user, $transaction, $currentBalance) {
        $loginUrl = $this->siteUrl . 'login.php';
        
        // Format transaction amount with currency symbol
        $formattedAmount = $transaction['currency'] . ' ' . number_format($transaction['amount'], 2);
        $formattedBalance = $transaction['currency'] . ' ' . number_format($currentBalance, 2);
        
        // Format transaction date
        $transactionDate = date('F j, Y, g:i a', strtotime($transaction['transaction_date']));
        
        // Determine transaction type display text
        $transactionTypeText = ucfirst($transaction['transaction_type']);
        
        // Create a simple HTML email if template doesn't exist
        if (!file_exists(__DIR__ . '/templates/transaction_notification.html')) {
            $htmlBody = "<h2>Transaction Notification</h2>";
            $htmlBody .= "<p>Dear {$user['first_name']},</p>";
            $htmlBody .= "<p>A {$transaction['transaction_type']} transaction has been processed on your account.</p>";
            $htmlBody .= "<p><strong>Amount:</strong> {$formattedAmount}<br>";
            $htmlBody .= "<strong>Date:</strong> {$transactionDate}<br>";
            $htmlBody .= "<strong>Reference:</strong> {$transaction['reference_number']}<br>";
            $htmlBody .= "<strong>Description:</strong> {$transaction['description']}<br>";
            $htmlBody .= "<strong>Current Balance:</strong> {$formattedBalance}</p>";
            $htmlBody .= "<p>If you did not authorize this transaction, please contact support immediately.</p>";
            
            return $this->sendMailInternal(
                $user['email'],
                $user['first_name'] . ' ' . $user['last_name'],
                $transactionTypeText . ' Transaction Alert - ' . $this->bankName,
                $htmlBody
            );
        }
        
        return $this->sendTemplatedEmail(
            $user['email'],
            $user['first_name'] . ' ' . $user['last_name'],
            $transactionTypeText . ' Transaction Alert - ' . $this->bankName,
            'transaction_notification',
            [
                'TRANSACTION_TYPE' => $transactionTypeText,
                'TRANSACTION_AMOUNT' => $formattedAmount,
                'TRANSACTION_DATE' => $transactionDate,
                'TRANSACTION_REFERENCE' => $transaction['reference_number'],
                'TRANSACTION_STATUS' => ucfirst($transaction['status']),
                'TRANSACTION_DESCRIPTION' => $transaction['description'] ?: 'N/A',
                'CURRENT_BALANCE' => $formattedBalance
            ],
            [
                'text' => 'View Account Details',
                'url' => $loginUrl
            ]
        );
    }
    
    /**
     * Send a password reset email
     * 
     * @param array $user User data including email, name
     * @param string $resetToken The password reset token
     * @return bool True if email was sent successfully
     */
    public function sendPasswordResetEmail($user, $resetToken) {
        $resetLink = $this->siteUrl . 'reset_password.php?token=' . $resetToken . '&email=' . urlencode($user['email']);
        
        return $this->sendTemplatedEmail(
            $user['email'],
            $user['first_name'] . ' ' . $user['last_name'],
            'Password Reset Request - ' . $this->bankName,
            'password_reset',
            [
                'RESET_LINK' => $resetLink
            ],
            [
                'text' => 'Reset Your Password',
                'url' => $resetLink
            ]
        );
    }
    
    /**
     * Send a security alert email
     * 
     * @param array $user User data including email, name
     * @param string $alertType Type of security alert
     * @param array $eventDetails Details about the security event
     * @return bool True if email was sent successfully
     */
    public function sendSecurityAlertEmail($user, $alertType, $eventDetails) {
        $loginUrl = $this->siteUrl . 'login.php';
        
        // Format event date
        $eventDate = date('F j, Y, g:i a', strtotime($eventDetails['date']));
        
        // Prepare alert message based on type
        $alertMessage = '';
        switch ($alertType) {
            case 'new_login':
                $alertMessage = 'Someone has logged into your account from a new device or location. If this was you, you can ignore this message.';
                break;
            case 'failed_login':
                $alertMessage = 'There were multiple failed login attempts on your account. We recommend changing your password immediately.';
                break;
            case 'password_changed':
                $alertMessage = 'Your account password was recently changed. If you did not make this change, please contact support immediately.';
                break;
            default:
                $alertMessage = 'A security event was detected on your account. Please review the details and take appropriate action if needed.';
        }
        
        return $this->sendTemplatedEmail(
            $user['email'],
            $user['first_name'] . ' ' . $user['last_name'],
            'Security Alert: ' . ucfirst(str_replace('_', ' ', $alertType)) . ' - ' . $this->bankName,
            'security_alert',
            [
                'ALERT_TYPE' => ucfirst(str_replace('_', ' ', $alertType)),
                'EVENT_DATE' => $eventDate,
                'IP_ADDRESS' => $eventDetails['ip_address'],
                'LOCATION' => $eventDetails['location'] ?? 'Unknown',
                'DEVICE' => $eventDetails['device'] ?? 'Unknown',
                'ALERT_MESSAGE' => $alertMessage
            ],
            [
                'text' => 'Secure Your Account',
                'url' => $loginUrl
            ]
        );
    }
    
    /**
     * Internal method to send an email using PHPMailer
     * 
     * @param string $to Recipient email
     * @param string $toName Recipient name
     * @param string $subject Email subject
     * @param string $htmlBody Email HTML content
     * @return bool True if email was sent successfully
     */
    private function sendMailInternal($to, $toName, $subject, $htmlBody) {
        $mail = new PHPMailer(true); // Passing `true` enables exceptions

        try {
            // Server settings from your config file
            $mail->isSMTP();
            $mail->Host       = SMTP_HOST;
            $mail->SMTPAuth   = true;
            $mail->Username   = SMTP_USERNAME;
            $mail->Password   = SMTP_PASSWORD;
            $mail->SMTPSecure = SMTP_SECURE;
            $mail->Port       = SMTP_PORT;

            // Recipients
            $mail->setFrom(MAIL_FROM_ADDRESS, MAIL_FROM_NAME);
            $mail->addAddress($to, $toName);

            // Content
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $htmlBody;
            $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $htmlBody)); // Plain text version

            $mail->send();
            return true;
        } catch (Exception $e) {
            // Log the detailed error for debugging
            error_log("PHPMailer Error: {$mail->ErrorInfo}");
            return false;
        }
    }
}
