<?php

namespace App\Livewire\Branches;

use App\Domain\Identity\Models\Branch;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('الفروع')]
class BranchList extends Component
{
    use WithPagination;

    public string $search = '';
    public bool $showInactive = false;

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

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

    public function toggleActive(string $uuid): void
    {
        $branch = Branch::where('uuid', $uuid)->firstOrFail();
        $branch->update(['is_active' => !$branch->is_active]);
    }

    public function render()
    {
        $query = Branch::query()
            ->when($this->search, fn ($q) => $q->where('name_ar', 'ilike', "%{$this->search}%")
                ->orWhere('name', 'ilike', "%{$this->search}%")
                ->orWhere('code', 'ilike', "%{$this->search}%"))
            ->when(!$this->showInactive, fn ($q) => $q->where('is_active', true))
            ->orderByDesc('is_main')
            ->orderBy('name_ar');

        return view('livewire.branches.branch-list', [
            'branches' => $query->paginate(15),
        ]);
    }
}
