<?php

namespace App\Livewire\Website;

use App\Domain\Website\Models\ContactSubmission;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('رسائل التواصل')]
class ContactSubmissionList extends Component
{
    use WithPagination, WithSorting;

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

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

    public function markAsRead(int $id): void
    {
        $submission = ContactSubmission::find($id);
        if ($submission && $submission->status->value === 'new') {
            $submission->update(['status' => 'read', 'read_at' => now()]);
        }
    }

    public function archive(int $id): void
    {
        ContactSubmission::find($id)?->update(['status' => 'archived']);
    }

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

    public function render()
    {
        $query = ContactSubmission::orderBy($this->sortBy, $this->sortDir);

        if ($this->status) {
            $query->where('status', $this->status);
        }

        return view('livewire.website.contact-submission-list', [
            'submissions' => $query->paginate(20),
        ]);
    }
}
