<?php

namespace App\Core;

/**
 * Email Template System
 * نظام قوالب البريد الإلكتروني
 */
class EmailTemplate
{
    private string $templatesPath;
    private array $variables = [];

    public function __construct(string $templatesPath = null)
    {
        $this->templatesPath = $templatesPath ?? __DIR__ . '/../../templates/email';
    }

    /**
     * تحميل template
     */
    public function load(string $templateName, array $variables = []): string
    {
        $templateFile = $this->templatesPath . '/' . $templateName . '.php';
        
        if (!file_exists($templateFile)) {
            throw new \Exception("Email template not found: {$templateName}");
        }

        $this->variables = $variables;
        
        // Extract variables
        extract($variables);
        
        // Capture output
        ob_start();
        include $templateFile;
        $content = ob_get_clean();

        return $content;
    }

    /**
     * Render template مع layout
     */
    public function render(string $templateName, array $variables = [], string $layout = 'default'): string
    {
        $content = $this->load($templateName, $variables);
        
        $layoutFile = $this->templatesPath . '/layouts/' . $layout . '.php';
        if (file_exists($layoutFile)) {
            $variables['content'] = $content;
            return $this->load('layouts/' . $layout, $variables);
        }

        return $content;
    }

    /**
     * إرسال email
     */
    public function send(string $to, string $subject, string $templateName, array $variables = [], string $layout = 'default'): bool
    {
        $body = $this->render($templateName, $variables, $layout);
        
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=UTF-8',
            'From: ' . ($variables['from'] ?? 'noreply@lablims.com'),
            'Reply-To: ' . ($variables['reply_to'] ?? 'noreply@lablims.com')
        ];

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

    /**
     * جلب قائمة templates المتاحة
     */
    public function getAvailableTemplates(): array
    {
        $templates = [];
        if (is_dir($this->templatesPath)) {
            $files = glob($this->templatesPath . '/*.php');
            foreach ($files as $file) {
                $name = basename($file, '.php');
                if ($name !== 'index' && strpos($name, 'layout') === false) {
                    $templates[] = $name;
                }
            }
        }
        return $templates;
    }
}
