<?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\Performance;
use App\Models\User;
use Validator;
use Auth;

class PerformanceController extends Controller
{

    public function performanceCreateUpdate(Request $request){

        $auth=Auth::user();

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

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

        } else {

            try{

                $data=[
                    'user_id','user_name','technical','organisation','status','date'
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                $obj['technical']=json_encode($request['technical']);
                $obj['organisation']=json_encode($request['organisation']);
                if($request->id>0){

                    try{

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

                    } catch (\Exception $e) {
                        return response(['error' => true, 'message' => 'Invalid Id to update'], 404); 
                    }
                }else{
                    $fromDate = date('Y-01-01'); // Start of the current year
                    $toDate = date('Y-12-31') . ' 23:59:59';  // End of the current year
                    
                    $checkPerformance = Performance::where('is_disabled', '0')
                        ->where('user_id', $request['user_id'])
                        ->where('status','!=','Declined')
                        ->where('updated_at', '>=', $fromDate)->where('updated_at', '<=', $toDate)
                        ->where('organisation_id', $auth['active_organisation'])
                        ->first();
                    
                    if ($checkPerformance !== null) {
                        return response()->json([
                            'message' => "Performance already exists for this year.",
                            'success' => false,
                            'vendor' => $checkPerformance
                        ]);
                    }
                    

                    $performance=Performance::create($obj);
                    // Log::info($performance);
                }

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


    public function getPerformance(Request $request){

        $user=Auth::user();

        if($user!=null){

            $performanceList=Performance::where('is_disabled','0')
                ->with(['employee', 'employee.department','employee.designation'])
                ->where('organisation_id',$user['active_organisation']);

            $performanceList=$this->fetchuserbyquery($performanceList,$request);
            $count=$performanceList->count();
            $sortOrder = ($request['sortOrder'] == 1) ? 'desc' : 'asc';
            $sortBy = $request['sortBy'] ?? 'id';             

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

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

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

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

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

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

        // get custom_date data by transaction_date
        if ($request['custom_date']!='' && isset($request['custom_date'])) {
            $customDate = $request->custom_date;
            $performanceList = $performanceList->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'
            $performanceList = $performanceList->whereBetween('created_at', [$fromDate, $toDate]);
        }

        return $performanceList;
    }

    public function getPerformancedetails(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()
            ]);
        }
    
        $performance = Performance::where('id', $request->id)
                        ->with(['employee', 'employee.department','employee.designation'])
                        ->where('organisation_id', $auth->active_organisation) 
                        ->first();
    
        if (!$performance) {
            return response()->json([
                'success' => false,
                'message' => 'Performance not found'
            ], 404);
        }
    
        $response = [
            'result' => $performance,
            'success' => true,
            'message' => 'Performance Details Retrieved Successfully.'
        ];
    
        return response()->json($response);
    }
    
    public function deletePerformance(Request $request){

        $auth=Auth::user();

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

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

       } else {

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

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

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

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

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

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

    public function updateStatusPerformance(Request $request){

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

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

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

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

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

}
