<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Service\OrganisationService;
use App\Models\Organisation;
use App\Models\UserOrganisation;
use App\Models\User;
use Validator;
use Log;

class OrganisationController extends Controller
{
    // Function for creating a new Organisation
    public function organisationCreateUpdate(Request $request){

        // Validation user and name  of organisation
        $validator=validator($request->all(),[
            'name'=>'required|string',
            'user_id'=>'required|exists:users,id', // this will validate user_id exists in users table
            'email'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            $user=Auth::user();
        
            // Creating object Service
            $organisationServie=new OrganisationService;
            $organisation=$organisationServie->organisationCreateUpdate($request,$user);

            $response=[
                'organisation'=>$organisation,
                'success' => true,
                'message' => 'Organisation Created Successfullly',
            ];

            return response()->json($response);
        }
    }

    // Function to fetch new Organisation
    public function fetchOrganisation(Request $request){

        $user=Auth::user();

        // getting  all the organisations from database of logged in user
        $organisation=Organisation::where('user_id',$user['id'])
            // ->with('organisation')
            ->get();

        foreach ($organisation as $key => $value) {
            // Getting Active Organisation
            if($value['organisation_id']==$user['active_organisation']){

                $value['is_active']=true;
            }else{
                $value['is_active']=false;
            }

            // Getting Primary organisation
            if($value['organisation_id']==$user['primary_organisation']){

                $value['is_primary']=true;
            }else{
                $value['is_primary']=false;
            }
        }

        $response=[
            'organisations'=>$organisation,
            'success' => true,
            'message' => 'Organisactions Fetched Successfullly',
        ];

            return response()->json($response);
        // }
    }

    public function switchOrganisation(Request $request){
        $user=Auth::user();

        // Validate Item
        $validator=validator($request->all(),[
            'organisation_id'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            $organisation_user=User::where('id',$user['id'])->first();

            // Check if Requested Organisation Present 
            $user_organisation=UserOrganisation::where('user_id',$user['id'])
                // ->whereHas('organisation',function($query) use ($request){
                //     $query->where('organisation_id',$request['organisation_id']);
                // })
                ->where('organisation_id',$request['organisation_id'])
                ->first();

            if($user_organisation!=null){

                $organisation_user['active_organisation']=$request['organisation_id'];
                $organisation_user->update();

                $response=[
                    'success'=>true,
                    'message'=>'Organisation Switched  Successfully',
                    'status'=>200,
                ];

            } else {
                $response=[
                    'success'=>false,
                    'message'=>'Organisation not belongs to User',
                    'status'=>200,
                ];
            }

            return response()->json($response);
        }
    }

    public function organisationDetails(Request $request){

         // Validate Item
         $validator=validator($request->all(),[
            'organisation_id'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            $organisation=Organisation::where('organisation_id',$request['organisation_id'])->first();

            $response=[
                'success'=> true,
                'details'=>$organisation
            ];

            return response()->json($response);
        }
    }

    // Deactivating User of the Organisation
    public function deactivateUser(Request $request){
         // Validate Item   

        $user=Auth::user();

        $validator=validator($request->all(),[
            'user_id'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            Log::info(print_r($request->all(),true));

            $obj['is_disabled']=1;

            
            try{
                $organisation_user=UserOrganisation::where('user_id',$request['user_id'])
                    ->where('organisation_id',$user['active_organisation'])
                    ->update($obj);


                    
                Log::info($organisation_user);

                // $organisation_user['is_disabled']=1;
                // $organisation_user->update();

                $response=[
                    'success'=>true,
                    'message'=>'User Deactivated  Successfully',
                    'status'=>200,
                ];

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['message' => 'Invalid Id to update '], 404);
            }

            return response()->json($response);
        }
    }

       // Setting Default Organisation
    public function default(Request $request){

        $user=Auth::user();
        // Validate Item
        $validator=validator($request->all(),[
           'organisation_id'=>'required'
       ]);

       if ($validator->fails()) { 
           return [
               'success' => false, 
               'message' => $validator->errors()->first()
           ];
       } else {

           $organisation=User::where('id',$user['id'])->first();

           $organisation_user=UserOrganisation::where('organisation_id',$request['organisation_id'])
                ->where('user_id',$user['id'])
                ->first();

            if($organisation_user!=null){

                $organisation['primary_organisation']=$request['organisation_id'];
                $organisation->update();
     
                $response=[
                    'success'=>true,
                    'message'=>'Organisation Set to Default Successfully',
                    'status'=>200,
                ];

            }else{

                $response=[
                    'success'=>false,
                    'message'=>'Organisation Id With User Not found',
                    'status'=>200,
                ];
            }

         

           return response()->json($response);
       }
    }

}
