<?php

namespace App\Models;

use App\Models\Concerns\BelongsToBranch;
use App\Models\Concerns\HasAuditColumns;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class CertificateTemplate extends Model
{
    use BelongsToBranch;
    use HasAuditColumns;
    use SoftDeletes;

    protected $fillable = ['branch_id', 'name', 'type', 'body', 'is_active'];

    protected function casts(): array
    {
        return ['is_active' => 'boolean'];
    }

    public const TYPES = [
        'character' => 'Character Certificate',
        'bonafide' => 'Bonafide Certificate',
        'leaving' => 'School Leaving Certificate',
        'experience' => 'Experience Certificate',
        'custom' => 'Custom',
    ];

    public function scopeActive(Builder $q): Builder
    {
        return $q->where('is_active', true);
    }

    /** Placeholders available to template authors. */
    public const PLACEHOLDERS = [
        'student_name', 'father_name', 'mother_name', 'admission_number', 'gr_number',
        'class', 'section', 'session', 'gender', 'dob', 'date', 'school', 'family_code',
    ];

    /** Render this template for a student into final HTML. */
    public function render(Student $student): string
    {
        $values = [
            'student_name' => $student->name,
            'father_name' => $student->family?->father_name ?? '',
            'mother_name' => $student->family?->mother_name ?? '',
            'admission_number' => $student->admission_number,
            'gr_number' => $student->gr_number ?? '',
            'class' => $student->schoolClass?->name ?? '',
            'section' => $student->section?->name ?? '',
            'session' => $student->academicSession?->name ?? '',
            'gender' => ucfirst($student->gender),
            'dob' => optional($student->date_of_birth)->format('d M Y') ?? '',
            'date' => now()->format('d M Y'),
            'school' => $student->branch?->name ?? config('app.name'),
            'family_code' => $student->family?->family_code ?? '',
        ];

        $body = $this->body;
        foreach ($values as $key => $val) {
            $body = str_replace(['{{'.$key.'}}', '{{ '.$key.' }}'], e($val), $body);
        }

        return $body;
    }
}
