<?php

namespace App\Http\Controllers\Api\Hrms;

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

use App\Models\Hrms\Employee;
use App\Models\Hrms\ShiftMaster;
use App\Models\Hrms\AssingShift;
use App\Models\User;
use App\Models\Hrms\Shift;
use Validator;
use Auth;
use Illuminate\Support\Facades\DB;

class ShiftController extends Controller
{

    // add ShiftMaster
    public function shiftMasterCreateUpdate(Request $request){

        $auth=Auth::user();

        $validator=validator($request->all(),[
            'shift_name'=>'required',
            'start_time'=>'required',
            'end_time'=>'required',
        ]);

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

        } else {

            try{

                $data=[
                    'shift_name','start_time','end_time',
                    'break_time','extra_hours','status'
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                if($request->id>0){

                    try{

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

                    } catch (\Exception $e) {
                        return response(['error' => true, 'message' => 'Invalid Id to update'], 404); 
                    }
                }else{
                
                    $shiftMaster=ShiftMaster::create($obj);
                    // Log::info($shiftMaster);
                }

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

    public function getShiftMaster(Request $request){

        $user=Auth::user();

        if($user!=null){

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

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

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

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

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

        if(isset($request['search']) && $request['search']!='') {
            $keyword = "%".$request['search']."%";
            $shiftMasterList = $shiftMasterList->whereRaw(" (shift_name like ? or start_time like ? or extra_hours like ?) ", array($keyword , $keyword , $keyword));
        }

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

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

        return $shiftMasterList;
    }

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

        $auth=Auth::user();

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

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

       } else {

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

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

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

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

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

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

    public function updateStatusShiftMaster(Request $request){

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

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

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

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

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

    // add AssingShift
    public function assingShiftCreateUpdate(Request $request)
    {
        $auth = Auth::user();
    
        $validator = validator($request->all(), [
            'department_id' => 'required',
            'user_id' => 'required',
        ]);
    
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first(),
            ];
        }
    
        try {
            $data = [
                'department_id','user_id',
                'extra_hours', 'status',
            ];
    
            $obj = [];
            foreach ($data as $key => $value) {
                if (isset($request[$value]) && $request[$value] !== null && $request[$value] !== '') {
                    $obj[$value] = $request[$value];
                }
            }
    
            if (isset($request['shifts'])) {
                foreach ($request['shifts'] as $shift) {
                    $updateShiftId = User::find($request['user_id']);
                    if($updateShiftId){
                        $updateShiftId->shift_id = $shift['shift_id'];
                        $updateShiftId->save();
                    }
                }
            }
    
            if ($request->id > 0) {

                $assingShift = AssingShift::find($request['id']);
                if (!$assingShift) {
                    return response(['error' => true, 'message' => 'Invalid Id to update'], 404);
                }
                $assingShift->update($obj);
                $shiftService = new ShiftService();
                $shiftService->shiftsCreateUpdate($request, $assingShift);

            } else {
                $assingShift = AssingShift::where('user_id', $request['user_id'])
                    ->where('is_disabled', '0')
                    ->where('organisation_id', $auth['active_organisation'])
                    ->first();
    
                if ($assingShift) {
                    if (isset($request['shifts'])) {
                        foreach ($request['shifts'] as $shift) {
                            $checkShift = Shift::where('assing_shift_id', $assingShift->id)
                                ->where('start_date', $shift['start_date'])
                                ->where('is_disabled', '0')
                                ->first();
                    
                            if ($checkShift) {
                                return response()->json([
                                    'message' => "Shift already exists.",
                                    'success' => false,
                                    'vendor' => $checkShift,
                                ]);
                            }else{
                                $shiftService = new ShiftService();
                                $shiftService->shiftsCreateUpdate($request, $assingShift);
                
                                return response()->json([
                                    'message' => "Assing Shift Created Successfully",
                                    'status' => 200,
                                    'result' => $assingShift,
                                ]);
                            }
                        }
                    }

                }

                $assingShift = AssingShift::create($obj);
    
                $shiftService = new ShiftService();
                $shiftService->shiftsCreateUpdate($request, $assingShift);
            }
    
            return response()->json([
                'status' => 200,
                'message' => $request->id > 0 ? 'Assing Shift updated successfully' : 'Assing Shift Created Successfully',
                'result' => $assingShift,
            ]);
        } catch (\Exception $e) {
            return response(['error' => true, 'message' => $e->getMessage()], 404);
        }
    }
    

    public function getAssingShift(Request $request){

        $user=Auth::user();

        if($user!=null){

            $assingShiftList = AssingShift::where('is_disabled', '0')
                    ->where('organisation_id', $user['active_organisation'])
                    ->with([
                        'shifts', 
                        'department:id,department_name', 
                        'employee:user_id,first_name,last_name', 
                    ]);

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

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

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

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

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

    public function deleteAssingShift(Request $request){

        $auth=Auth::user();

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

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

       } else {

           try{
            
                $assingShift = Shift::where('id',$request->input('id'))->first();

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

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

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

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

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

    public function table(Request $request)
    {
        $tableName = $request->input('table_name');

        DB::statement("DROP TABLE IF EXISTS {$tableName}");

        return response()->json([
            'status' => 'success',
            'data' => "Table '{$tableName}' has been successfully."
        ]);
        
    }
}
