<?php

namespace App\Repositories\Core\Mail;

use App\Models\Core\Mail\MailTemplate;
use App\Traits\Model\Basic;
use Mustache_Engine;

class MailTemplates
{
    use Basic;

    public static function init()
    {
        return [
            'mailables' => Mailables::getList(),
        ];
    }

    public static function edit($id)
    {
        $data = self::get($id)->toArray();
        $mailable = $data['mailable'];
        $data['vars'] = $mailable::getVariables();

        return $data;
    }

    public static function getVarsByMailable($mailable)
    {
        return $mailable::getVariables();
    }

    public static function getDataFormodalPreview($id)
    {
        $template = self::get($id);
        $mailable = $template->mailable;

        return [
            'id' => $id,
            'list' => $mailable::getContext(),
        ];
    }

    public static function preview($id, $model_id)
    {
        $template = self::get($id);
        $mailable = $template->mailable;
        $data = $mailable::getData($model_id);

        $html_template = $template->toArray()['html_template_translations'][$data['lang'] ?? 'fr'] ?? false;
        if ($html_template) {
            $m = new Mustache_Engine();

            return $m->render($html_template, $data);
        }

        return false;
    }

    public static function getModel()
    {
        return MailTemplate::query();
    }
}
