<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

class EmailService {
    private $mailer;
    private $fromEmail;
    private $fromName;
    private $templatePath;

    public function __construct() {
        $this->mailer = new PHPMailer(true);
        $this->templatePath = __DIR__ . '/../templates/emails/';
        
        try {
            // Server settings
            $this->mailer->isSMTP();
            $this->mailer->Host = $_ENV['SMTP_HOST'];
            $this->mailer->SMTPAuth = true;
            $this->mailer->Username = $_ENV['SMTP_USERNAME'];
            $this->mailer->Password = $_ENV['SMTP_PASSWORD'];
            $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $this->mailer->Port = $_ENV['SMTP_PORT'];
            
            $this->fromEmail = $_ENV['MAIL_FROM_ADDRESS'];
            $this->fromName = $_ENV['MAIL_FROM_NAME'];
            
            $this->mailer->setFrom($this->fromEmail, $this->fromName);
            $this->mailer->isHTML(true);
            
        } catch (Exception $e) {
            error_log("Email service initialization error: " . $e->getMessage());
            throw new Exception('Email service configuration error');
        }
    }

    public function sendWelcomeEmail($to, $data) {
        try {
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($to);
            $this->mailer->Subject = 'Welcome to First National Bank Incorporated - Account Created Successfully';
            
            $body = $this->getWelcomeEmailTemplate($data);
            $this->mailer->Body = $body;
            $this->mailer->AltBody = strip_tags($body);
            
            return $this->mailer->send();
        } catch (Exception $e) {
            error_log("Failed to send welcome email to {$to}: " . $e->getMessage());
            return false;
        }
    }

    public function sendVerificationEmail($to, $data) {
        try {
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($to);
            $this->mailer->Subject = 'Verify Your Email Address';
            
            $body = $this->getVerificationEmailTemplate($data);
            $this->mailer->Body = $body;
            $this->mailer->AltBody = strip_tags($body);
            
            return $this->mailer->send();
        } catch (Exception $e) {
            error_log("Failed to send verification email to {$to}: " . $e->getMessage());
            return false;
        }
    }

    private function getWelcomeEmailTemplate($data) {
        ob_start();
        include $this->templatePath . 'welcome.php';
        return ob_get_clean();
    }

    private function getVerificationEmailTemplate($data) {
        ob_start();
        include $this->templatePath . 'verification.php';
        return ob_get_clean();
    }
}
