<?php

namespace App\Livewire;

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

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

    public function mount(): void
    {
        $user = auth()->user();
        $this->isPinned = $user->preferred_branch_id !== null;

        if (session()->has('active_branch_id')) {
            $value = session('active_branch_id');
            $this->selectedBranch = $value === null ? 'all' : (string) $value;
        } else {
            $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]);
            $this->isPinned = false;
        } else {
            $branchId = (int) $value;
            session(['active_branch_id' => $branchId]);
            auth()->user()->update(['preferred_branch_id' => $branchId]);
            $this->isPinned = true;
        }

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

    public function unpin(): void
    {
        auth()->user()->update(['preferred_branch_id' => null]);
        $this->isPinned = false;
    }

    public function pin(): void
    {
        if ($this->selectedBranch !== 'all') {
            auth()->user()->update(['preferred_branch_id' => (int) $this->selectedBranch]);
            $this->isPinned = true;
        }
    }

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