<?php

namespace App\Models;

use App\Models\BaseModel;

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

    // ✅ Laravel will auto-manage created_at / updated_at
    public $timestamps = false;

    protected $fillable = [
        'code',
        'variant',
        'subject',
        'body_html',
        'is_active',
        'updated_by',
        'updated_at',
    ];

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

    /**
     * Fetch a template by code and variant, falling back to 'default' if needed.
     * Active only.
     */
    public static function getTemplate(string $code, string $variant = 'default'): ?array
    {
        $row = static::query()
            ->where('code', $code)
            ->where('variant', $variant)
            ->where('is_active', 1)
            ->first();

        if ($row) {
            return $row->toArray();
        }

        $fallback = static::query()
            ->where('code', $code)
            ->where('variant', 'default')
            ->where('is_active', 1)
            ->first();

        return $fallback?->toArray();
    }
}
