<?php

namespace App\Livewire\Admin;

use App\Models\MailTemplate;
use App\Services\Mail\MailTemplateRenderer;
use Livewire\Attributes\Validate;
use LivewireUI\Modal\ModalComponent;

/**
 * Edit one template in a modal.
 *
 * R20: a textarea growing inside a table row pushes every column beside it and
 * reads like a rendering fault rather than a form. A modal is also the only
 * place a five-line body has room.
 *
 * A modal is reachable WITHOUT the page's route middleware, so it authorises
 * again and reads the record itself rather than trusting a property the browser
 * hydrated.
 */
class EditMailTemplate extends ModalComponent
{
    public string $uuid = '';

    #[Validate('required|string|max:255')]
    public string $name = '';

    #[Validate('required|string|max:255')]
    public string $subject = '';

    #[Validate('required|string|max:5000')]
    public string $body = '';

    public bool $active = true;

    public function mount(string $uuid): void
    {
        $this->authorize('customers.manage');

        $template = MailTemplate::query()->where('uuid', $uuid)->firstOrFail();

        $this->uuid = $uuid;
        $this->name = $template->name;
        $this->subject = $template->subject;
        $this->body = $template->body;
        $this->active = (bool) $template->active;
    }

    public function save()
    {
        $this->authorize('customers.manage');

        $data = $this->validate();

        MailTemplate::query()->where('uuid', $this->uuid)->update([
            'name' => trim($data['name']),
            'subject' => trim($data['subject']),
            'body' => $data['body'],
            'active' => $this->active,
        ]);

        $this->dispatch('notify', message: __('templates.saved'));

        return $this->redirectRoute('admin.templates', navigate: true);
    }

    public function render()
    {
        return view('livewire.admin.edit-mail-template', [
            'placeholders' => MailTemplateRenderer::PLACEHOLDERS,
        ]);
    }
}
