<?php

namespace App\Http\Controllers\Api\Hrms;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \App\Models\Travel;
use Validator;
use Auth;

class TravelController extends Controller
{
    
    public function travelCreateUpdate(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','department_id','purposeofvisit',
                    'placeofvisit','expected_date_of_arrival','expected_date_of_departure',
                    'expected_duration_in_days','is_billable','customer_name',
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                if($request->id>0){

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

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

                    $travel=Travel::create($obj);
                }

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


    public function getTravel(Request $request){

        $user=Auth::user();

        if($user!=null){

            $travelList=Travel::where('is_disabled','0')->with('department:id,department_name','employee')
               ->where('organisation_id',$user['active_organisation']);

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

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

            $response=[
                'travel'=>$travelList,
                'count'=>$count,
                'message'=>'Successful',
            ];

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

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

        if(isset($request['search']) && $request['search']!='') {
            $keyword = "%".$request['search']."%";
            $travelList = $travelList->whereRaw(" (purposeofvisit like ? or placeofvisit like ? or customer_name like ?) ", array($keyword , $keyword , $keyword));
        }

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

        return $travelList;
    }

    public function detailsTravel(Request $request){

        $auth=Auth::user();

        try{

            $travel=Travel::where('id',$request['id'])->with('department:id,department_name','employee')
                ->where('organisation_id',$auth['active_organisation'])
                ->first();

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

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

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

    public function deleteTravel(Request $request){

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

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

       } else {

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

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

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

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

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

    public function travelByuserId(Request $request){

        $auth=Auth::user();

        try{

            $travelByuserId=Travel::where('user_id',$request['user_id'])->where('is_disabled','0')
                ->with('department:id,department_name','employee')
                ->where('organisation_id',$auth['active_organisation'])
                ->get();

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

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

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

}
