<?php

namespace App\Livewire\Branches;

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

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

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

    public function mount(): void
    {
        if (!request()->has('sortBy')) {
            $this->sortBy = 'name_ar';
        }
        if (!request()->has('sortDir')) {
            $this->sortDir = 'asc';
        }
    }

    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))
            ->orderBy($this->sortBy, $this->sortDir);

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