<?php

namespace App\Http\Controllers\Api\Hrms;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \App\Models\Hrms\Designation;
use \App\Models\Hrms\Employee;
use \App\Models\Hrms\Department;
use Validator;
use Auth;

class DesignationController extends Controller
{

    public function designationCreateUpdate(Request $request){

        $auth=Auth::user();

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

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

        } else {

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

                if($request[$value]==''){
                    $obj[$value]=null;
                }
            }

            if($request->id>0){

                try{

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

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

                $checkdesignation=Designation::where('designation_name',$request['designation_name'])
                            ->where('organisation_id',$auth['active_organisation'])
                            ->first();

                if($checkdesignation !=null){

                    $response=[
                        'message'=>"Designation id already exist",
                        'success'=>false,
                        'vendor'=>$checkdesignation
                    ];

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

                $designation=Designation::create($obj);

            }

            return response()->json([
                'status'=>200,
                'message'=> $request->id>0 ? 'Designation update successfully':'Designation Created Successfully',
                'designation'=>$designation],
            200);

        }
    }

    public function getDesignation(Request $request){

        $user=Auth::user();

        if($user!=null){

            $userlist=Designation::where('is_disabled','0')->with('department:id,department_name','enteredby')
                ->where('organisation_id',$user['active_organisation']);

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

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

            $response=[
                'designation'=>$userlist,
                'count'=>$count,
                'message'=>'Successful',
            ];

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

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

        if(isset($request['search']) && $request['search']!='') {
            $keyword = "%".$request['search']."%";
            $userlist = $userlist->whereRaw(" (designation_name like ? or department_id like ? or description like ?) ", array($keyword , $keyword , $keyword));
        }

        // get custom_date data by transaction_date
        if ($request['department_id']!='' && isset($request['department_id'])) {
            $department_id = $request->department_id;
            $userlist = $userlist->where('department_id', $department_id);
        }

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

        return $userlist;
    }

    public function detailsDesignation(Request $request){

        $user=Auth::user();

        try{

            $designation=Designation::where('id',$request['id'])->with('department:id,department_name','enteredby')
                                ->where('organisation_id',$user['active_organisation'])
                                ->first();
            $response=[
                'success'=>true,
                'designation'=>$designation
            ];

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

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

    public function deleteDesignation(Request $request){

        $user=Auth::user();

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

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

       } else {

           try{
                $designation =  Designation::where('id',$request->input('id'))
                                        ->where('organisation_id',$user['active_organisation'])
                                        ->first();

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

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

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

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

    public function getDesignationEmp(Request $request){

        $user=Auth::user();

        try{

            $getDesignationEmp=Employee::where('designation_id',$request['designation_id'])->where('is_disabled','0')
                                ->where('organisation_id',$user['active_organisation'])
                                ->get();
            $response=[
                'success'=>true,
                'getDesignationEmp'=>$getDesignationEmp
            ];

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

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

    
    public function getDesignationByDeparmentId(Request $request){

        $user=Auth::user();

        try{

            $getDesignation=Designation::where('department_id',$request['department_id'])
                                ->where('is_disabled','0')
                                ->where('organisation_id',$user['active_organisation'])
                                ->get();
            $response=[
                'success'=>true,
                'getDesignation'=>$getDesignation
            ];

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

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