<?php

namespace App\Http\Controllers\Api\Hrms;

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

class DepartmentController extends Controller
{
    public function departmentCreateUpdate(Request $request){

        $auth=Auth::user();

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

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

        } else {

            try{

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

                if($request->id>0){

                    try{
                        $department=Department::findOrFail($request['id']);
                        $department->update($obj);

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

                    $checkDepartment=Department::where('department_name',$request['department_name'])
                                ->where('organisation_id',$auth['active_organisation'])
                                ->first();

                    if($checkDepartment !=null){

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

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

                    $department=Department::create($obj);
                }

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


    public function getDepartment(Request $request){

        $user=Auth::user();

        if($user!=null){

            $userlist=Department::where('is_disabled','0')
                ->with([
                    'parentDepartment:id,department_name',
                    'departmentHead:id,first_name,last_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=[
                'department'=>$userlist,
                'count'=>$count,
                'message'=>'Successful',
            ];

        } else {
            $response=[
                'department'=>$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(" (department_name like ? or department_head like ? or parent_department like ?) ", array($keyword , $keyword , $keyword));
        }

        // 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 detailsDepartment(Request $request){

        $auth=Auth::user();

        try{

            $department=Department::where('id',$request['id'])
                ->with([
                    'parentDepartment:id,department_name',
                    'departmentHead:id,first_name,last_name',
                    'enteredby'
                ])
                ->where('organisation_id',$auth['active_organisation'])
                ->first();

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

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

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

    public function deleteDepartment(Request $request){

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

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

       } else {

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

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

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

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

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

    public function getDepartmentEmp(Request $request){

        $user=Auth::user();

        try{

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

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

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

    public function getDepartmentProjects(Request $request){

        $auth=Auth::user();

        try{

            $getProject=Project::where('department_id',$request['department_id'])->where('is_disabled','0')
                ->with('client:id,full_name')
                ->where('organisation_id',$auth['active_organisation'])
                ->get();

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

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

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