<?php

namespace App\Components\Template;

use App\Models\Contact\ContactCategory;
use App\Models\Contact\Template;
use App\Services\HistoryService;
use Livewire\Component;

class Editor extends Component {
    public ?Template $template = null;
    public $category_id, $title, $subject, $content, $type = 'email';

    protected $rules = [
        'title' => 'required|min:3',
        'category_id' => 'required|exists:contact_categories,id',
        'content' => 'required',
        'type' => 'required'
    ];

    public function mount() {
        $this->authorize($this->template ? 'templates.edit' : 'templates.create');
        if ($this->template) {
            $this->category_id = $this->template->category_id;
            $this->title = $this->template->title;
            $this->subject = $this->template->subject;
            $this->content = $this->template->content;
            $this->type = $this->template->type;
        } else {
            $this->content = "<h1>Hello {{name}}</h1>\n<p>Your message here...</p>";
        }
    }

    public function save(HistoryService $history) {
        $this->authorize($this->template?->id ? 'templates.edit' : 'templates.create');
        $this->validate();

        $isNew = empty($this->template?->id);

        $template = Template::updateOrCreate(
            ['id' => $this->template?->id],
            [
                'category_id' => $this->category_id,
                'title' => $this->title,
                'subject' => $this->subject,
                'content' => $this->content,
                'type' => $this->type,
            ]
        );

        $history->addForActor(($isNew ? 'Created' : 'Updated') . " {$this->type} template '{$this->title}'", [
            'template_id' => $template->id,
            'title'       => $this->title,
            'type'        => $this->type,
        ]);

        return redirect()->route('templates.index');
    }

    public function render() {
        return view('components.template.editor', [
            'categories' => ContactCategory::all()
        ]);
    }
}
