<?php
// 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 : 'First National Bank Incorporated';
        $this->bankLogo = defined('BANK_LOGO') ? BANK_LOGO : BASE_URL . 'assets/img/logo.png';
        $this->bankAddress = defined('BANK_ADDRESS') ? BANK_ADDRESS : '5Rue du Centre 394, 7020 Masnuy-Saint-Jean';
        $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 existing sendEmail function
            return $this->sendEmail($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
            ]
        );
    }
    
    /**
     * 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 sendEmail($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;
        }
    }
}
