<?php

declare(strict_types=1);

namespace App\Livewire\Admin\EmailTemplates;

use App\Models\EmailTemplate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.admin')]
final class Index extends Component
{
    public ?int $editingId = null;

    public string $name = '';

    public string $key = '';

    public string $subject = '';

    public string $body = '';

    public bool $isActive = true;

    #[Computed]
    public function templates()
    {
        return EmailTemplate::query()->latest()->get();
    }

    protected function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:120'],
            'key' => ['required', 'string', 'max:100'],
            'subject' => ['required', 'string', 'max:255'],
            'body' => ['required', 'string', 'min:10'],
            'isActive' => ['boolean'],
        ];
    }

    public function edit(int $templateId): void
    {
        $template = EmailTemplate::findOrFail($templateId);
        $this->editingId = (int) $template->id;
        $this->name = $template->name;
        $this->key = $template->key;
        $this->subject = $template->subject;
        $this->body = $template->body;
        $this->isActive = (bool) $template->is_active;
    }

    public function save(): void
    {
        $validated = $this->validate();

        $payload = [
            'name' => $validated['name'],
            'key' => $validated['key'],
            'subject' => $validated['subject'],
            'body' => $validated['body'],
            'is_active' => (bool) $validated['isActive'],
        ];

        if ($this->editingId) {
            EmailTemplate::query()->whereKey($this->editingId)->update($payload);
            session()->flash('success', 'Email template updated.');
        } else {
            EmailTemplate::query()->create($payload);
            session()->flash('success', 'Email template created.');
        }

        $this->reset(['editingId', 'name', 'key', 'subject', 'body']);
        $this->isActive = true;
    }

    public function render()
    {
        return view('livewire.admin.email-templates.index');
    }
}
