<?php

namespace App\Http\Controllers\Api\Hrms;

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

class QuickLinksController extends Controller
{
    
    public function quickLinksCreateUpdate(Request $request){

        $auth=Auth::user();

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

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

        } else {

            try{

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

                $obj['user_id']=$auth['id'];
                if($request->id>0){

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

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

                    $quickLinks=QuickLinks::create($obj);
                }

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


    public function getQuickLinks(Request $request){

        $user=Auth::user();

        if($user!=null){

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

            $quickLinksList=$this->fetchuserbyquery($quickLinksList,$request);

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

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

            $response=[
                'quickLinks'=>$quickLinksList,
                'count'=>$count,
                'message'=>'Successful',
            ];

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

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

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

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

        return $quickLinksList;
    }

    public function detailsQuickLinks(Request $request){

        $auth=Auth::user();

        try{

            $quickLinks=QuickLinks::where('id',$request['id'])
                ->where('organisation_id',$auth['active_organisation'])
                ->first();

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

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

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

    public function deleteQuickLinks(Request $request){

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

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

       } else {

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

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

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

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

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


}
