<?php

namespace App\Livewire;

use App\Domain\Identity\Models\Branch;
use Livewire\Component;

class BranchSwitcher extends Component
{
    public ?int $activeBranchId = null;

    public function mount(): void
    {
        $this->activeBranchId = session('active_branch_id', auth()->user()->branch_id);

        if (!$this->activeBranchId) {
            $first = Branch::where('is_active', true)->first();
            if ($first) {
                $this->activeBranchId = $first->id;
                session(['active_branch_id' => $first->id]);
            }
        }
    }

    public function updatedActiveBranchId($value): void
    {
        if ($value === 'all') {
            session(['active_branch_id' => null]);
            $this->activeBranchId = null;
        } else {
            $branchId = (int) $value;
            session(['active_branch_id' => $branchId]);
            $this->activeBranchId = $branchId;
        }

        $this->dispatch('branch-switched', branchId: $this->activeBranchId);
        $this->redirect(request()->header('Referer', '/'), navigate: true);
    }

    public function render()
    {
        return view('livewire.branch-switcher', [
            'branches' => Branch::where('is_active', true)->get(['id', 'name_ar', 'code']),
        ]);
    }
}
