<?php

namespace App\Core;

/**
 * Email Service - خدمة إرسال البريد الإلكتروني
 * يدعم SMTP و mail() function
 */
class EmailService
{
    private array $config;
    private EmailTemplate $template;
    private ?\PHPMailer\PHPMailer\PHPMailer $mailer = null;

    public function __construct(array $config = [])
    {
        $this->config = $config;
        $this->template = new EmailTemplate();
        
        // محاولة استخدام PHPMailer إذا كان متوفراً
        if (class_exists('\PHPMailer\PHPMailer\PHPMailer')) {
            $this->mailer = new \PHPMailer\PHPMailer\PHPMailer(true);
            $this->configureMailer();
        }
    }

    /**
     * إعداد PHPMailer
     */
    private function configureMailer(): void
    {
        if (!$this->mailer) {
            return;
        }

        $smtp = $this->config['smtp'] ?? [];
        
        if (!empty($smtp['enabled'])) {
            $this->mailer->isSMTP();
            $this->mailer->Host = $smtp['host'] ?? 'localhost';
            $this->mailer->Port = $smtp['port'] ?? 587;
            $this->mailer->SMTPAuth = !empty($smtp['auth']);
            $this->mailer->Username = $smtp['username'] ?? '';
            $this->mailer->Password = $smtp['password'] ?? '';
            $this->mailer->SMTPSecure = $smtp['encryption'] ?? 'tls';
        }

        $this->mailer->CharSet = 'UTF-8';
        $this->mailer->isHTML(true);
        $this->mailer->setFrom(
            $this->config['from_email'] ?? 'noreply@lablims.com',
            $this->config['from_name'] ?? 'Smart Lab LIMS'
        );
    }

    /**
     * إرسال email
     */
    public function send(string $to, string $subject, string $template, array $variables = [], string $layout = 'default'): bool
    {
        try {
            $body = $this->template->render($template, $variables, $layout);

            if ($this->mailer) {
                return $this->sendWithPHPMailer($to, $subject, $body);
            }

            return $this->sendWithMail($to, $subject, $body);
        } catch (\Throwable $e) {
            error_log("Email send error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * إرسال مع PHPMailer
     */
    private function sendWithPHPMailer(string $to, string $subject, string $body): bool
    {
        if (!$this->mailer) {
            return false;
        }

        try {
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($to);
            $this->mailer->Subject = $subject;
            $this->mailer->Body = $body;
            
            return $this->mailer->send();
        } catch (\Throwable $e) {
            error_log("PHPMailer error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * إرسال مع mail() function
     */
    private function sendWithMail(string $to, string $subject, string $body): bool
    {
        $headers = [
            'MIME-Version: 1.0',
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . ($this->config['from_email'] ?? 'noreply@lablims.com'),
            'Reply-To: ' . ($this->config['reply_to'] ?? 'noreply@lablims.com')
        ];

        return mail($to, $subject, $body, implode("\r\n", $headers));
    }

    /**
     * إرسال email بسيط
     */
    public function sendSimple(string $to, string $subject, string $message): bool
    {
        $variables = [
            'content' => nl2br(htmlspecialchars($message, ENT_QUOTES, 'UTF-8')),
            'subject' => $subject
        ];

        return $this->send($to, $subject, 'welcome', $variables);
    }
}
