<?php

namespace App\Models;

use App\Models\BaseModel;

class EmailTemplate extends BaseModel
{
    protected $table = 'email_templates';

    // legacy model didn't specify timestamps; keep off unless your table has created_at/updated_at.
    public $timestamps = true;

    protected $fillable = [
        'template_key',
        'name',
        'subject',
        'body',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'updated_by' => 'integer',
    ];

    public static function getTemplate(string $code, string $variant = 'default'): ?self
    {
        $row = static::query()
            ->where('code', $code)
            ->where('is_active', 1)
            ->where(function ($q) use ($variant) {
                $q->where('variant', $variant)
                  ->orWhere('variant', 'default');
            })
            ->orderByRaw("CASE WHEN variant = ? THEN 0 ELSE 1 END", [$variant])
            ->first();

        return $row;
    }

    /**
     * Equivalent of legacy getActiveTemplates():
     * is_active=1, orderBy template_key ASC
     */
    public static function getActiveTemplates()
    {
        return static::query()
            ->where('is_active', 1)
            ->orderBy('template_key', 'asc')
            ->get();
    }

    /**
     * Equivalent of legacy findByKey():
     * template_key = $key AND is_active=1
     */
    public static function findByKey(string $key): ?self
    {
        return static::query()
            ->where('template_key', $key)
            ->where('is_active', 1)
            ->first();
    }
}
