<?php

namespace App\Components\Template;

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

class Index extends Component {
    public $showCategoryForm = false;
    public $newCategoryName;

    public $templates;

    public function mount() {
        $this->authorize('templates.view');
        $this->templates = Template::all();
    }

    public function saveCategory(HistoryService $history) {
        $this->authorize('templates.create');
        $this->validate(['newCategoryName' => 'required|unique:contact_categories,name']);
        $category = ContactCategory::create(['name' => $this->newCategoryName]);

        $history->addForActor("Created template category '{$this->newCategoryName}'", [
            'category_id' => $category->id,
            'name'        => $this->newCategoryName,
        ]);

        $this->newCategoryName = '';
        $this->showCategoryForm = false;
    }

    public function deleteTemplate($id, HistoryService $history) {
        $this->authorize('templates.delete');
        $template = Template::find($id);
        $context = ['template_id' => $id, 'title' => $template?->title, 'type' => $template?->type];
        Template::destroy($id);

        $history->addForActor("Deleted template '" . ($context['title'] ?? $id) . "'", $context);
    }

    public function render() {
        return view('components.template.index');
    }
}