<?php

namespace App\Livewire\WhatsApp;

use App\Domain\WhatsApp\Enums\MessageStatus;
use App\Domain\WhatsApp\Enums\MessageType;
use App\Domain\WhatsApp\Models\WhatsAppMessage;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('سجل رسائل الواتساب')]
class MessageLog extends Component
{
    use WithPagination;

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

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

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

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

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

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

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

    public function render()
    {
        $query = WhatsAppMessage::query()
            ->with('sender:id,name')
            ->when($this->search, function ($q) {
                $q->where(function ($q2) {
                    $q2->where('phone_number', 'ilike', "%{$this->search}%")
                       ->orWhere('content', 'ilike', "%{$this->search}%");
                });
            })
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->when($this->type, fn ($q) => $q->where('type', $this->type))
            ->orderByDesc('created_at');

        return view('livewire.whatsapp.message-log', [
            'messages' => $query->paginate(25),
            'statuses' => MessageStatus::cases(),
            'types' => MessageType::cases(),
        ]);
    }
}
