<?php

namespace App\Http\Controllers\Api\Hrms;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

use App\Models\Hrms\Employee;
use App\Models\Hrms\Training;
use App\Models\Hrms\Trainer;
use App\Models\User;
use Validator;
use Auth;

class TrainingController extends Controller
{

    // Trainer
    public function trainerCreateUpdate(Request $request){

        $auth=Auth::user();

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

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

        } else {

            try{

                $data=[
                    'user_id','trainer_name','email','training_type','mobile_no','start_date','end_date',
                    'duration','role','trainer_cost','description'
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                if($request->id>0){

                    try{

                        $trainer=Trainer::findOrFail($request['id']);
                        $trainer->update($obj);

                    } catch (\Exception $e) {
                        return response(['error' => true, 'message' => 'Invalid Id to update'], 404); 
                    }
                }else{

                    $trainer=Trainer::create($obj);
                    // Log::info($trainer);
                }

                return response()->json([
                    'status'=>200,
                    'message'=> $request->id>0 ? 'Trainer update successfully':'Trainer Created Successfully',
                    'result'=>$trainer
                ],200);
                
            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
        }
    }


    public function getTrainer(Request $request){

        $user=Auth::user();

        if($user!=null){

            $trainerList=Trainer::where('is_disabled','0')
                ->where('organisation_id',$user['active_organisation']);

            $trainerList=$this->fetchuserbyquery($trainerList,$request);
            $count=$trainerList->count();

            $sortOrder = ($request['sortOrder'] == 1) ? 'desc' : 'asc';
            $sortBy = $request['sortBy'] ?? 'id';

            $trainerList = $trainerList->orderby($sortBy,$sortOrder)
                ->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                ->get();

            $response=[
                'result'=>$trainerList,
                'count'=>$count,
                'message'=>'Successful',
            ];

        } else {
            $response=[
                'result'=>$trainerList,
                'count'=>$count,
                'message'=>'Invalid User'
            ];
        }

        return response()->json($response);
    }
    
    // Filter Users
    public function fetchuserbyquery($trainerList,$request){

        if(isset($request['search']) && $request['search']!='') {
            $keyword = "%".$request['search']."%";
            $trainerList = $trainerList->whereRaw(" (trainer_name like ? or email like ? or role like ? or training_type like ? or mobile_no like ?) ", 
            array($keyword , $keyword , $keyword , $keyword , $keyword));
        }

        if($request['status']!='' && isset($request['status'])){
            $trainerList=$trainerList->where('status',$request['status']);
        }

        // get custom_date data by transaction_date
        if ($request['custom_date']!='' && isset($request['custom_date'])) {
            $customDate = $request->custom_date;
            $trainerList = $trainerList->whereDate('created_at', $customDate);
        }

        // get fromDate toDate data by created_at
        if ($request['fromDate']!='' && isset($request['toDate'])) {
            $fromDate = $request->fromDate;
            $toDate = $request->toDate;
        
            // 'fromDate' and 'toDate'
            $trainerList = $trainerList->whereBetween('created_at', [$fromDate, $toDate]);
        }

        return $trainerList;
    }

    public function getTrainerdetails(Request $request) {
        $response = [];
        $auth = Auth::user();
        
        // Validate Input
        $validator = Validator::make($request->all(), [
            'id' => 'required'
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first()
            ]);
        }
    
        $trainer = Trainer::where('id', $request->id)
                        ->with('enteredby')
                        ->where('organisation_id', $auth->active_organisation) 
                        ->first();
    
        if (!$trainer) {
            return response()->json([
                'success' => false,
                'message' => 'Trainer not found'
            ], 404);
        }
    
        $response = [
            'result' => $trainer,
            'success' => true,
            'message' => 'Trainer Details Retrieved Successfully.'
        ];
    
        return response()->json($response);
    }
    
    public function deleteTrainer(Request $request){

        $auth=Auth::user();

        $validator=validator($request->all(),[
           'id'=>'required|integer'
        ]);

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

       } else {

           try{
                $trainer = Trainer::where('id',$request->input('id'))
                            ->where('organisation_id',$auth['active_organisation'])
                            ->first();

                if (!$trainer) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Trainer not found'
                    ], 404);
                }

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

                $response=[
                    'success'=>true,
                    'message'=>'Trainer Deleted successfully.'
                ];

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

            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
       }
    }

    public function updateStatusTrainer(Request $request){

        $auth=Auth::user();
        
        $validator=validator($request->all(),[
            'id'=>'required|integer'
         ]);
 
        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first(),
            ];
 
        } else {

            try{
                
                $trainer = Trainer::where('id',$request->input('id'))->first();
                $trainer['status']=$request['status'];
                $trainer->update();

                $response=[
                    'success'=>true,
                    'message'=>'Status Updated successfully.',
                    'result'=>$trainer
                ];

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

            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
        }
    }


    // Training
    public function trainingCreateUpdate(Request $request){

        $auth=Auth::user();

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

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

        } else {

            try{

                $data=[
                    'training_type','trainer_id','user_id','start_date','end_date','duration',
                    'training_cost','description','status','user_name','trainer_name'
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                if($request->id>0){

                    try{

                        $training=Training::findOrFail($request['id']);
                        $training->update($obj);

                    } catch (\Exception $e) {
                        return response(['error' => true, 'message' => 'Invalid Id to update'], 404); 
                    }
                }else{

                    $training=Training::create($obj);
                    // Log::info($training);
                }

                return response()->json([
                    'status'=>200,
                    'message'=> $request->id>0 ? 'Training update successfully':'Training Created Successfully',
                    'result'=>$training
                ],200);
                
            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
        }
    }


    public function getTraining(Request $request){

        $user=Auth::user();

        if($user!=null){

            $trainingList=Training::where('is_disabled','0')->with('trainer')->with('employe:id,first_name,last_name')
                ->where('organisation_id',$user['active_organisation']);

            $trainingList=$this->fetchuserbyquerytrainingList($trainingList,$request);
            $count=$trainingList->count();

            $sortOrder = ($request['sortOrder'] == 1) ? 'desc' : 'asc';
            $sortBy = $request['sortBy'] ?? 'id';

            $trainingList = $trainingList->orderby($sortBy,$sortOrder)
                ->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                ->get();

            $response=[
                'result'=>$trainingList,
                'count'=>$count,
                'message'=>'Successful',
            ];

        } else {
            $response=[
                'result'=>$trainingList,
                'count'=>$count,
                'message'=>'Invalid User'
            ];
        }

        return response()->json($response);
    }
    
    // Filter Users
    public function fetchuserbyquerytrainingList($trainingList,$request){

        if(isset($request['search']) && $request['search']!='') {
            $keyword = "%".$request['search']."%";
            $trainingList = $trainingList->whereRaw(" (training_type like ? or user_name like ? or trainer_name like ? or status like ?) ", 
            array($keyword , $keyword , $keyword , $keyword));
        }

        if($request['status']!='' && isset($request['status'])){
            $trainingList=$trainingList->where('status',$request['status']);
        }

        // get custom_date data by transaction_date
        if ($request['custom_date']!='' && isset($request['custom_date'])) {
            $customDate = $request->custom_date;
            $trainingList = $trainingList->whereDate('created_at', $customDate);
        }

        // get fromDate toDate data by created_at
        if ($request['fromDate']!='' && isset($request['toDate'])) {
            $fromDate = $request->fromDate;
            $toDate = $request->toDate;
        
            // 'fromDate' and 'toDate'
            $trainingList = $trainingList->whereBetween('created_at', [$fromDate, $toDate]);
        }

        return $trainingList;
    }

    public function getTrainingdetails(Request $request) {
        $response = [];
        $auth = Auth::user();
        
        // Validate Input
        $validator = Validator::make($request->all(), [
            'id' => 'required'
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first()
            ]);
        }
    
        $training = Training::where('id', $request->id)->with('trainer')->with('employe:id,first_name,last_name','enteredby')
                        ->where('organisation_id', $auth->active_organisation) 
                        ->first();
    
        if (!$training) {
            return response()->json([
                'success' => false,
                'message' => 'Training not found'
            ], 404);
        }
    
        $response = [
            'result' => $training,
            'success' => true,
            'message' => 'Training Details Retrieved Successfully.'
        ];
    
        return response()->json($response);
    }
    
    public function deleteTraining(Request $request){

        $auth=Auth::user();

        $validator=validator($request->all(),[
            'id'=>'required|integer'
        ]);

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

        } else {

            try{
                $training = Training::where('id',$request->input('id'))
                            ->where('organisation_id',$auth['active_organisation'])
                            ->first();

                if (!$training) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Training not found'
                    ], 404);
                }

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

                $response=[
                    'success'=>true,
                    'message'=>'Training Deleted successfully.'
                ];

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

            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
        }
    }

    public function updateStatusTraining(Request $request){

        $auth=Auth::user();
        
        $validator=validator($request->all(),[
            'id'=>'required|integer'
            ]);
    
        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first(),
            ];
    
        } else {

            try{
                
                $training = Training::where('id',$request->input('id'))->first();
                $training['status']=$request['status'];
                $training->update();

                $response=[
                    'success'=>true,
                    'message'=>'Status Updated successfully.',
                    'result'=>$training
                ];

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

            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
        }
    }

    public function trainingByuserId(Request $request) {
        $response = [];
        $auth = Auth::user();
        
        // Validate Input
        $validator = Validator::make($request->all(), [
            'trainer_id' => 'required'
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first()
            ]);
        }
    
        $trainingByuserId = Training::where('trainer_id', $request->trainer_id)->with('employe:id,first_name,last_name')
                        ->where('organisation_id', $auth->active_organisation) 
                        ->get();
    
        if (!$trainingByuserId) {
            return response()->json([
                'success' => false,
                'message' => 'Training not found'
            ], 404);
        }
    
        $response = [
            'result' => $trainingByuserId,
            'success' => true,
            'message' => 'Training Details Retrieved Successfully.'
        ];
    
        return response()->json($response);
    }
}
