<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\HR\RoleAndPermission;
use App\Models\StudentInformation\StudentBasicDetails;
use App\Models\HR\StaffInformation;
class CheckLoginSource
{
    public function handle(Request $request, Closure $next)
    {
        
        $source = $request->header('X-Login-Source'); 
        

        
        if (!$source) {
            $source = 'web';
        }

        
        $response = $next($request);

       
        if ($request->user()) {
            $role = $request->user()->role;
            
            $studnetBasicDetails = StudentBasicDetails::where('user_id', $request->user()->id)->exists();
            $staffDetails = StaffInformation::where('staffId', $request->user()->id)->exists();
            if ($studnetBasicDetails) {
               if ($source === 'web') {
                    return response()->json([
                        'error' => 'You are not authorized to login in Web Application. Please use Android Application.'
                    ], 403);
                } 
            }
            if ($staffDetails) { 
                $roleAndPermission = RoleAndPermission::where('id', $role)->first();
                if (!$roleAndPermission) {
                    return response()->json([
                        'error' => 'Role and Permission not found.'
                    ], 403);
                }
                if ($source === 'web' && !$roleAndPermission->isWebAccess) {
                    return response()->json([
                        'error' => 'You are not authorized to login in Web Application. Please use Android Application.'
                    ], 403);
                }

                if ($source === 'android' && !$roleAndPermission->isAndroidAccess) {
                    return response()->json([
                        'error' => 'You are not authorized to login in Android Application. Please use Web Application.'
                    ], 403);
                }
            }
        }

        return $response;
    }
}
