<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\DB;

class FetchCampusId
{

    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();
        $schoolId = $user->school_id;

            
            $request->merge(['school_id' => $schoolId]);
        /* if ($user && $user->role == 1) {
            
            $schoolId = $user->id;

            
            $request->merge(['school_id' => $schoolId]);


        } elseif ($user && $user->role == 2) {
            $schoolId = $user->associated_id;

            
            $request->merge(['school_id' => $schoolId]);
        } elseif ($user && $user->role == 4) {

            $schoolId = $user->id;

            
            $request->merge(['school_id' => $schoolId]);


        } elseif ($user && $user->role == 5) {
            
            $schoolId = $user->id;

            
            $request->merge(['school_id' => $schoolId]);


        } elseif ($user && $user->role == 6) {
            $schoolId = $user->associated_id;

            
            $request->merge(['school_id' => $schoolId]);
        } elseif ($user && $user->role == 7) {
            $checkingId = $user->associated_id;

            $role = DB::table('users')->where('id', $checkingId)->value('role');
            if ($role == 5) {
                $schoolId = $checkingId;
            } elseif ($role == 6) {
                $schoolId = DB::table('users')->where('id', $checkingId)->value('associated_id');
            } else {
                $schoolId = null;
            }

            $request->merge(['school_id' => $schoolId]);
        } elseif ($user && $user->role == 8) {
            $checkingId = $user->associated_id;
            $role = DB::table('users')->where('id', $checkingId)->value('role');
            if ($role == 5) {
                $schoolId = $checkingId;
            } elseif ($role == 6) {
                $schoolId = DB::table('users')->where('id', $checkingId)->value('associated_id');
            } else {
                $schoolId = null;
            }
            $request->merge(['school_id' => $schoolId]);
        } else {
            $request->merge(['school_id' => null]);
        }
 */
        return $next($request);
    }
}
