<?php
// includes/mail/MailService.php

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

class MailService {
    private $config;

    /**
     * MailService constructor.
     * Loads the SMTP configurations from config/smtp.php.
     */
    public function __construct() {
        $configPath = __DIR__ . '/../../../config/smtp.php';
        if (!file_exists($configPath)) {
            throw new \Exception("SMTP configuration file not found at: " . $configPath);
        }
        $this->config = require $configPath;
    }

    /**
     * Create and configure a new PHPMailer instance.
     * 
     * @return PHPMailer
     */
    private function getMailer() {
        // Attempt to load PHPMailer using Composer autoloader, with fallback to manual include.
        if (file_exists(__DIR__ . '/../../../vendor/autoload.php')) {
            require_once __DIR__ . '/../../../vendor/autoload.php';
        } else {
            require_once __DIR__ . '/../PHPMailer/Exception.php';
            require_once __DIR__ . '/../PHPMailer/PHPMailer.php';
            require_once __DIR__ . '/../PHPMailer/SMTP.php';
        }

        $mail = new PHPMailer(true);

        // Server settings
        $mail->isSMTP();
        $mail->Host       = $this->config['host'];
        $mail->Port       = $this->config['port'];
        $mail->SMTPAuth   = $this->config['auth_enabled'];
        $mail->Username   = $this->config['username'];
        $mail->Password   = $this->config['password'];
        $mail->SMTPSecure = $this->config['encryption'] === 'tls' ? PHPMailer::ENCRYPTION_STARTTLS : PHPMailer::ENCRYPTION_SMTPS;
        
        // Timeout
        $mail->Timeout = 10;

        // Default sender
        $mail->setFrom($this->config['from_email'], $this->config['from_name']);

        return $mail;
    }

    /**
     * Send event registration confirmation email.
     * 
     * @param string $recipientEmail
     * @param array $details Keys: fullName, eventTitle, registrationId, paymentStatus, eventDate, venue, reportingTime, supportContact
     * @return bool Success or Failure
     */
    public function sendRegistrationConfirmation($recipientEmail, $details) {
        try {
            require_once __DIR__ . '/EmailTemplates.php';
            $htmlBody = EmailTemplates::getRegistrationConfirmation($details);

            $mail = $this->getMailer();
            $mail->addAddress($recipientEmail, $details['fullName'] ?? '');
            $mail->isHTML(true);
            $mail->Subject = 'Registration Confirmed - ' . ($details['eventTitle'] ?? 'Supernova 2.0');
            $mail->Body    = $htmlBody;

            return $mail->send();
        } catch (Exception $e) {
            error_log("PHPMailer Exception in sendRegistrationConfirmation: " . $e->getMessage());
            return false;
        } catch (\Exception $e) {
            error_log("General Exception in sendRegistrationConfirmation: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Send generic HTML email notification.
     * 
     * @param string $recipientEmail
     * @param string $recipientName
     * @param string $subject
     * @param string $messageBody
     * @return bool Success or Failure
     */
    public function sendGenericEmail($recipientEmail, $recipientName, $subject, $messageBody) {
        try {
            require_once __DIR__ . '/EmailTemplates.php';
            $htmlBody = EmailTemplates::getGenericTemplate($subject, $messageBody);

            $mail = $this->getMailer();
            $mail->addAddress($recipientEmail, $recipientName);
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $htmlBody;

            return $mail->send();
        } catch (Exception $e) {
            error_log("PHPMailer Exception in sendGenericEmail: " . $e->getMessage());
            return false;
        } catch (\Exception $e) {
            error_log("General Exception in sendGenericEmail: " . $e->getMessage());
            return false;
        }
    }
}
