<?php

namespace App\Service;

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

class MailService
{
    protected $mailer;

    public function __construct()
    {
        $this->mailer = new PHPMailer(true); // Passing true enables exceptions
        
        // SMTP Configuration
        $this->mailer->isSMTP();
        $this->mailer->Host = env('MAIL_HOST');
        $this->mailer->SMTPAuth = true;
        $this->mailer->Username = env('MAIL_USERNAME');
        $this->mailer->Password = env('MAIL_PASSWORD');
        $this->mailer->SMTPSecure = 'tls';
        $this->mailer->Port = env('MAIL_PORT');
        
        // From address
        $this->mailer->setFrom(
            env('MAIL_FROM_ADDRESS'),
            env('MAIL_FROM_NAME')
        );
    }

    /**
     * Send an email using PHPMailer
     *
     * @param string $email Recipient email address
     * @param string $subject Email subject
     * @param string $messageContent HTML or plain text content
     * @param bool $isHtml Whether the content is HTML (default: true)
     * @return bool True on success, false on failure
     */
    public function sendEmail($email, $subject, $messageContent, $isHtml = true)
    {
        try {
            // Recipient
            $this->mailer->addAddress($email);
            
            // Content
            $this->mailer->isHTML($isHtml);
            $this->mailer->Subject = $subject;
            $this->mailer->Body = $messageContent;
            
            // Add plain text alternative for non-HTML mail clients
            if ($isHtml) {
                $this->mailer->AltBody = strip_tags($messageContent);
            }
            
            $this->mailer->send();
            return true;
            
        } catch (Exception $e) {
            // Log the error
            error_log("Mailer Error: " . $this->mailer->ErrorInfo);
            return false;
        } finally {
            // Clear addresses for next email
            $this->mailer->clearAddresses();
            $this->mailer->clearAttachments();
        }
    }
}