<?php

namespace App\Livewire\People;

use App\Domain\Identity\Models\Person;
use App\Livewire\Concerns\AppliesRoleScope;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('السجل العام')]
class PersonList extends Component
{
    use WithPagination, AppliesRoleScope;

    protected string $scopePermission = 'people.list';

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

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

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

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

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

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

    public function deletePerson(int $id): void
    {
        $this->authorize('people.delete');

        DB::transaction(function () use ($id) {
            $person = Person::findOrFail($id);

            if ($person->user_id) {
                User::where('id', $person->user_id)->first()?->delete();
            }

            $person->delete();
        });

        session()->flash('success', 'تم حذف الشخص بنجاح');
    }

    public function render()
    {
        $query = Person::query()
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('name_ar', 'ILIKE', "%{$search}%")
                       ->orWhere('name', 'ILIKE', "%{$search}%")
                       ->orWhere('national_id', 'like', "%{$search}%")
                       ->orWhere('phone', 'like', "%{$search}%");
                });
            })
            ->when($this->gender, fn ($q) => $q->where('gender', $this->gender))
            ->when($this->classification, fn ($q) => $q->where('classification', $this->classification))
            ->orderBy('name_ar');

        $this->applyRoleScope($query);

        return view('livewire.people.person-list', [
            'people' => $query->paginate(20),
        ]);
    }
}
