<?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 {
            $user = auth()->user();
            $branchId = $user->preferred_branch_id ?? $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]);
            auth()->user()->update(['preferred_branch_id' => null]);
        } else {
            $branchId = (int) $value;
            session(['active_branch_id' => $branchId]);
            auth()->user()->update(['preferred_branch_id' => $branchId]);
        }

        $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']),
        ]);
    }
}
