<?php

namespace App\Http\Controllers;

use App\Models\BranchModel;
use App\Models\CompanyModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SetupController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $companies = $user->companies;
        $image = CompanyModel::first();

        return view('auth.setup', compact('companies', 'image'));
    }

    public function getBranches($id)
    {

        $user = Auth::user();
        $companyId = $id;

        if ($user->companies->contains('id', $companyId)) {
            $branches = BranchModel::where('company_id', $companyId)
                ->whereHas('users', function ($query) use ($user) {
                    $query->where('user_id', $user->id);
                })
                ->get();

            return response()->json(['branches' => $branches]);
        }

        return response()->json(['branches' => []]);
    }

    public function setup(Request $request)
    {
        $request->validate([
            'company' => 'required',
            'branch' => 'required'
        ]);

        $user = Auth::user();
        $companyId = $request->input('company');
        $branchId = $request->input('branch');

        if (
            !$user->companies->contains('id', $companyId) ||
            !BranchModel::where('id', $branchId)
                ->where('company_id', $companyId)
                ->whereHas('users', function ($query) use ($user) {
                    $query->where('user_id', $user->id);
                })->exists()
        ) {
            return back()->with('error', 'Invalid company or branch selection');
        }

        session([
            'comp_id' => $companyId,
            'branch_id' => $branchId,
        ]);
        if (Auth::user()->user_flg !== 'C') {
            return redirect()->route('dashboard');
        } else {
            return redirect()->route('orders-index');
        }
    }

    public function switchBranch(Request $request)
    {

        $branch_id = $request->branchID;
        $company_id = BranchModel::where('id', $branch_id)->value('company_id');

        session([
            'comp_id' => $company_id,
            'branch_id' => $branch_id,
        ]);

        return response()->json(['message' => 'Branch switched successfully.']);
    }

}