<?php

namespace App\Modules\PLATFORM\Settings\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\PLATFORM\Settings\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class BranchSelectorController extends Controller
{
    /**
     * Show branch selector page
     */
    public function show()
    {
        $user = Auth::user();
        $branches = $user->branches;
        $company = Company::first();
        // If user has no branches, show error
        if ($branches->isEmpty()) {
            return redirect()->route('home')
                ->with('error', 'You are not assigned to any branch. Please contact administrator.');
        }

        // If user has only one branch, auto-select it
        if ($branches->count() === 1) {
            session(['current_branch_id' => $branches->first()->id]);
            return redirect()->intended(route('home'));
        }

        view()->share([
            'currentCompany'     => $company,
            'currentBranch'      => null,
            'isSuperAdmin'       => false,
            'availableBranches' => $user->branches, // ONLY assigned branches
        ]);
        
        // Show branch selection page
        return view('settings::core/branch-selector', compact('branches'));
    }

    /**
     * Select a branch
     */
    public function select(Request $request)
    {
       
        $branchId = $request->input('branch_id');
        $user = Auth::user();

        if (!$user->hasAccessToBranch($branchId)) {
            return redirect()->route('branch.select')
                ->with('error', 'You do not have access to this branch.');
        }

        session(['current_branch_id' => $branchId]);

        return redirect()->intended(route('home'));
    }

    /**
     * Switch to a different branch
     */
    public function switch(Request $request)
    {
        $branchId = $request->input('branch_id');
        $user = Auth::user();

        // Super admin can select any branch OR all branches
        if ($user->hasRole('super-admin')) {
            session(['current_branch_id' => $branchId ?: null]);
            return redirect()->back();
        }

        // Regular user must have access
        if (!$branchId || !$user->hasAccessToBranch($branchId)) {
            return redirect()->route('branch.select')
                ->with('error', 'You do not have access to this branch.');
        }

        session(['current_branch_id' => $branchId]);

        return redirect()->back();
    }
}
