<?php
namespace App\Services;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use App\Models\EmailQueue;

class EmailService
{
    protected PHPMailer $mailer;

    public function __construct()
    {
        $this->mailer = new PHPMailer(true);

        $this->mailer->isSMTP();
        $this->mailer->Host = MAIL_HOST;
        $this->mailer->SMTPAuth = true;
        $this->mailer->Username = MAIL_USERNAME;
        $this->mailer->Password = MAIL_PASSWORD;
        $this->mailer->SMTPSecure = MAIL_ENCRYPTION === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
        $this->mailer->Port = MAIL_PORT;

        $this->mailer->setFrom(MAIL_FROM_EMAIL, MAIL_FROM_NAME);
        $this->mailer->isHTML(true);
    }

    /**
     * Send a single email
     */
    public function sendEmail(
        string $to,
        string $subject,
        string $body,
        ?string $fromEmail = null,
        ?string $fromName = null
    ): bool {
        try {
            $this->mailer->clearAddresses();
            $this->mailer->clearReplyTos();

            

            // Dynamic sender
            if ($fromEmail) {
                $this->mailer->setFrom(
                    $fromEmail,
                    $fromName ?? MAIL_FROM_NAME
                );
            } else {
                $this->mailer->setFrom(
                    MAIL_FROM_EMAIL,
                    MAIL_FROM_NAME
                );
            }

            $this->mailer->addAddress($to);
            $this->mailer->Subject = $subject;
            $this->mailer->Body = $body;

            return $this->mailer->send();
        } catch (Exception $e) {
            error_log("EmailService Error: " . $e->getMessage());
            return false;
        }
    }


    /**
     * Send multiple queued emails
     */
    public function sendQueuedEmails(array $emails): void
    {
        foreach ($emails as $email) {
            $sent = $this->sendEmail(
                $email['recipient_email'],
                $email['subject'],
                $email['body'],
                $email['sender_email'] ?? null,
                $email['sender_name'] ?? null
            );

            EmailQueue::updateStatus(
                $email['id'],
                $sent ? 'sent' : 'failed',
                $sent ? date('Y-m-d H:i:s') : null
            );
        }
    }

}
