<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class BranchController extends Controller
{
    public function select(): View|RedirectResponse
    {
        $user = auth()->user();
        $branches = $user->branches;

        if ($branches->isEmpty()) {
            return redirect()->route('portal.login')->withErrors(['email' => 'No branches assigned to this account.']);
        }

        if ($branches->count() === 1) {
            $user->update(['active_branch_id' => $branches->first()->id]);

            return redirect()->route('portal.dashboard');
        }

        return view('portal.branches.select', compact('branches'));
    }

    public function update(Request $request): RedirectResponse
    {
        $request->validate([
            'branch_id' => ['required', 'exists:branches,id'],
        ]);

        $user = auth()->user();

        // Ensure the branch belongs to the user
        if (! $user->branches()->where('id', $request->branch_id)->exists()) {
            return back()->withErrors(['branch_id' => 'Invalid branch selected.']);
        }

        $user->update(['active_branch_id' => $request->branch_id]);

        return redirect()->route('portal.dashboard');
    }
}
