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

class LeaveController extends Controller
{

    // LeaveMaster
    public function leaveMasterCreateUpdate(Request $request){

        $auth=Auth::user();

        $validator=validator($request->all(),[
            'leave_type'=>'required',
            'type_of_leave'=>'required',
            'available_days'=>'required|numeric',
        ]);

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

        } else {

            try{

                $data=[
                    'leave_type',
                    'type_of_leave',
                    'available_days',
                    'status',
                    'description',
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                if($request->id>0){

                    try{

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

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

                    $leaveMaster=LeaveMaster::create($obj);
                    // Log::info($leaveMaster);
                }

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


    public function getLeaveMaster(Request $request){

        $user=Auth::user();

        if($user!=null){

            $leaveMaster=LeaveMaster::where('is_disabled','0')
                // ->where('organisation_id',$user['active_organisation'])
                ->with('enteredby');
                 
            $leaveMaster=$this->fetchuserbyquery($leaveMaster,$request);
            $count=$leaveMaster->count();
            $totalannualLeave=$leaveMaster->sum('available_days');

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

            $response=[
                'result'=>$leaveMaster,
                'count'=>$count,
                'total_annual_leave'=>$totalannualLeave,
                'message'=>'Successful',
            ];

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

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

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

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

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

        return $leaveMaster;
    }

    public function getleaveMasterdetails(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()
            ]);
        }
    
        $leaveMaster = LeaveMaster::where('id', $request->id)
                        // ->where('organisation_id', $auth->active_organisation) 
                        ->with('enteredby')
                        ->first();
    
        if (!$leaveMaster) {
            return response()->json([
                'success' => false,
                'message' => 'LeaveMaster not found'
            ], 404);
        }
    
        $response = [
            'result' => $leaveMaster,
            'success' => true,
            'message' => 'LeaveMaster Details Retrieved Successfully.'
        ];
    
        return response()->json($response);
    }
    
    public function deleteLeaveMaster(Request $request){

        $auth=Auth::user();

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

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

       } else {

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

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

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

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

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

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

    public function updateStatusLeaveMaster(Request $request){

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

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

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

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

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

    // Leave apply
    public function leaveCreateUpdate(Request $request){

        $auth=Auth::user();

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

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

        } else {

            try{

                $data=[
                    'user_id','name','leave_type_id','leave_type_name','from_date','to_date',
                    'type_of_leave','days','resion',
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                if($request->id>0){

                    try{

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

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

                    $leave=Leave::create($obj);
                    // Log::info($leave);
                }

                return response()->json([
                    'status'=>200,
                    'message'=> $request->id>0 ? 'Leave Update Successfully':'Leave Created Successfully',
                    'result'=>$leave
                ],200);
                
            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
        }
    }
    
    public function getLeave(Request $request){

        $user=Auth::user();

        if($user!=null){

            $leave=Leave::where('is_disabled','0')
                ->with('enteredby')
                ->where('organisation_id',$user['active_organisation']);
                 
            if(isset($request['search']) && $request['search']!='') {
                $keyword = "%".$request['search']."%";
                $leave = $leave->whereRaw(" (name like ? or leave_type_name like ? or status like ? ) ", 
                array($keyword , $keyword , $keyword));
            }
    
            if($request['status']!='' && isset($request['status'])){
                $leave=$leave->where('status',$request['status']);
            }

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

            $todayDate = date('Y-m-d');
            $total_count=$leave->count();
            $overall_count= (clone $leave)->whereDate('created_at', $todayDate)->count();
            $approved_leaves_count= (clone $leave)->where('status','Approved')->whereDate('updated_at', $todayDate)->count();
            $pending_leaves_count= (clone $leave)->where('status','Pending')->whereDate('updated_at', $todayDate)->count();
            $decliend_leaves_count= (clone $leave)->where('status','Declined')->whereDate('updated_at', $todayDate)->count();
            
            $sortOrder = ($request['sortOrder'] == 1) ? 'desc' : 'asc';
            $sortBy = $request['sortBy'] ?? 'id';

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

            $response=[
                'result'=>$leave,
                'total_count'=>$total_count,
                'overall_count'=>$overall_count,
                'approved_leaves_count'=>$approved_leaves_count,
                'pending_leaves_count'=>$pending_leaves_count,
                'decliend_leaves_count'=>$decliend_leaves_count,
                'message'=>'Successful',
            ];

        } else {
            $response=[
                'result'=>$leave,
                'total_count'=>$total_count,
                'overall_count'=>$overall_count,
                'approved_leaves_count'=>$approved_leaves_count,
                'pending_leaves_count'=>$pending_leaves_count,
                'decliend_leaves_count'=>$decliend_leaves_count,
                'message'=>'Invalid User'
            ];
        }

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

    public function getLeavedetails(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()
            ]);
        }
    
        $leave = Leave::where('id', $request->id)
                ->with('enteredby')
                        ->where('organisation_id', $auth->active_organisation) 
                        ->first();
    
        if (!$leave) {
            return response()->json([
                'success' => false,
                'message' => 'Leave not found'
            ], 404);
        }
    
        $response = [
            'result' => $leave,
            'success' => true,
            'message' => 'Leave Details Retrieved Successfully.'
        ];
    
        return response()->json($response);
    }


    public function deleteLeave(Request $request){

        $auth=Auth::user();

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

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

       } else {

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

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

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

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

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

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

    public function updateStatusLeave(Request $request){

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

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

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

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

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

    public function leaveByuserId(Request $request){

        $auth=Auth::user();

        try{

            $leaveByuserId=Leave::where('user_id',$request['user_id'])->where('is_disabled','0')
                ->where('organisation_id',$auth['active_organisation'])
                ->get();

            $response=[
                'success'=>true,
                'leaveByuserId'=>$leaveByuserId
            ];

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

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

    public function leaveSummaryByUserId(Request $request)
    {
        $auth = Auth::user();
    
        try {
            $leaveMaster = LeaveMaster::where('is_disabled', '0')
                ->where('organisation_id', $auth['active_organisation'])
                ->get();
    
            $leaveSummary = [];
    
            foreach ($leaveMaster as $leaveType) {
                $bookedDays = Leave::where('leave_type_id', $leaveType->id)
                    ->where('user_id', $request->user_id)
                    ->where('is_disabled', '0')->selectRaw("IFNULL(SUM(CAST(REGEXP_SUBSTR(days, '[0-9]+') AS UNSIGNED)), 0) as total_days")
                    ->value('total_days'); // Sum up 'days' from Leave model
    
                $leaveSummary[] = [
                    'leave_type' => $leaveType->leave_type, 
                    'available_days' => $leaveType->available_days,
                    'booked_days' => $bookedDays,
                ];
            }
    
            $response = [
                'success' => true,
                'leave_summary' => $leaveSummary,
            ];
    
            return response()->json($response);
    
        } catch (\Exception $e) {
            return response(['error' => true, 'message' => $e->getMessage()], 404);
        }
    }
    
}
