<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class EmailTemplate extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'subject',
        'body',
        'variables',
        'type',
        'is_active',
        'description',
        'metadata',
    ];

    protected $casts = [
        'variables' => 'array',
        'metadata' => 'array',
        'is_active' => 'boolean',
    ];

    /**
     * Get the template type options from database
     */
    public static function getTypeOptions()
    {
        return EmailTemplateType::active()
            ->ordered()
            ->pluck('name', 'slug')
            ->toArray();
    }

    /**
     * Get static type options (fallback)
     */
    public static function getStaticTypeOptions()
    {
        return [
            'general' => 'General',
            'learner' => 'Learner',
            'admin' => 'Administrator',
            'system' => 'System',
            'notification' => 'Notification',
        ];
    }

    /**
     * Get available variables for templates
     */
    public static function getAvailableVariables()
    {
        return [
            'company' => [
                'company_name' => 'Company Name',
                'company_email' => 'Company Email',
                'company_phone' => 'Company Phone',
                'company_address' => 'Company Address',
            ],
            'learner' => [
                'learner_first_name' => 'Learner First Name',
                'learner_last_name' => 'Learner Last Name',
                'learner_email' => 'Learner Email',
                'learner_phone' => 'Learner Phone',
                'learner_full_name' => 'Learner Full Name',
            ],
            'admin' => [
                'admin_first_name' => 'Admin First Name',
                'admin_last_name' => 'Admin Last Name',
                'admin_email' => 'Admin Email',
                'admin_full_name' => 'Admin Full Name',
            ],
            'system' => [
                'site_name' => 'Site Name',
                'site_url' => 'Site URL',
                'current_date' => 'Current Date',
                'current_time' => 'Current Time',
                'year' => 'Current Year',
            ],
            'logo' => [
                'company_logo' => 'Company Logo',
                'site_logo' => 'Site Logo',
                'logo_url' => 'Logo URL',
            ],
            'enrollment' => [
                'enrollment_date' => 'Enrollment Date',
                'course_name' => 'Course Name',
                'course_duration' => 'Course Duration',
                'completion_date' => 'Completion Date',
            ],
        ];
    }

    /**
     * Process template variables and replace them with actual values
     */
    public function processTemplate($data = [])
    {
        $subject = $this->subject;
        $body = $this->body;

        // Replace variables in subject
        foreach ($data as $key => $value) {
            $subject = str_replace('{' . $key . '}', $value, $subject);
        }

        // Replace variables in body
        foreach ($data as $key => $value) {
            // Special handling for logo variables - convert to HTML img tag
            if (in_array($key, ['company_logo', 'site_logo', 'logo_url']) && !empty($value)) {
                $imgTag = '<img src="' . $value . '" alt="Logo" style="max-width: 200px; height: auto;">';
                $body = str_replace('{' . $key . '}', $imgTag, $body);
            } else {
                $body = str_replace('{' . $key . '}', $value, $body);
            }
        }

        return [
            'subject' => $subject,
            'body' => $body,
        ];
    }

    /**
     * Scope for active templates
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope for templates by type
     */
    public function scopeByType($query, $type)
    {
        return $query->where('type', $type);
    }

    /**
     * Get the template type model
     */
    public function templateType()
    {
        return $this->belongsTo(EmailTemplateType::class, 'type', 'slug');
    }
}
