<?php

namespace App\Livewire;

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

class BranchSwitcher extends Component
{
    public string $selectedBranch = 'all';

    public function mount(): void
    {
        if (session()->has('active_branch_id')) {
            $value = session('active_branch_id');
            $this->selectedBranch = $value === null ? 'all' : (string) $value;
        } else {
            // First visit — default to user's assigned branch or first active
            $branchId = auth()->user()->branch_id;
            if (!$branchId) {
                $first = Branch::where('is_active', true)->first();
                $branchId = $first?->id;
            }
            $this->selectedBranch = $branchId ? (string) $branchId : 'all';
            session(['active_branch_id' => $branchId]);
        }
    }

    public function updatedSelectedBranch($value): void
    {
        if ($value === 'all') {
            session(['active_branch_id' => null]);
        } else {
            session(['active_branch_id' => (int) $value]);
        }

        $this->dispatch('branch-switched');
        $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']),
        ]);
    }
}
