<?php

namespace App\Livewire\Admin;

use App\Models\SentMail;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

/**
 * Everything this installation has sent, newest first.
 *
 * "Hat der Kunde die Zugangsdaten je bekommen, und wann?" used to be answered
 * on the mail server — a different machine, a different program, and nothing an
 * operator can put in front of somebody who says nothing ever arrived.
 *
 * A row means the transport accepted the message. What the receiving server did
 * with it afterwards is not ours to know, and a column claiming otherwise would
 * be worse than none.
 */
#[Layout('layouts.admin')]
class MailLog extends Component
{
    use WithPagination;

    #[Url]
    public string $search = '';

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

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

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

        $mails = SentMail::query()
            ->with('customer')
            ->when($this->search !== '', function ($q) {
                $term = '%'.$this->search.'%';
                $q->where(fn ($w) => $w->where('to', 'like', $term)->orWhere('subject', 'like', $term));
            })
            ->latest('sent_at')
            ->latest('id')
            ->paginate(30);

        return view('livewire.admin.mail-log', ['mails' => $mails]);
    }
}
