<?php

namespace App\Http\Controllers\v2019;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Validator;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Auth\User;

class Alert extends Controller
{
    public function getAlerts(Request $request)
    {
        $memId = \App\Helper::getMemId();
        //$data = json_decode($request->getContent(), true);
        $data["section"] = $request->input("section");
        $data["memId"] = $request->input("memid");
        $data["eventID"] = $request->input("eventID");
        $data["resource"] = $request->input("resourceType");

        $validator = Validator::make($data, [
            'section' => 'required',
            'memId' => 'int',
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
		
		if (isset($data['priceType'])) {
            $xDaysBefore = $data['priceType'];
        }
		
        $alertIds = \App\Alert::select('item_id',"status")
            ->where('section', 'like', ''.$data['section'].'%')
            ->where('memid', $memId)
            ->where('event_id', (isset($data['eventID']) ? $data['eventID'] : 0))
            ->where('resourceType',$data["resource"]);
			
		if ($request->has("priceType") && $request->input("priceType")!='') {
            $alertIds = $alertIds->where('x_days_before',$request->input("priceType"));
        }
        
		$alertIds = $alertIds->get();
            //->where('status', 'active')
        ///$alertIds->get();
		
        $val = array();    
        foreach($alertIds as $v ){
            $val[] = $v->item_id."-".$v->status;
        }       
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg,
            ],
            'data' => (!empty($alertIds) ? implode(",",$val) : "")
        ]);
    }

    public function toggleAlerts(Request $request)
    {
        $memId = \App\Helper::getMemId();
		if($request->has("rid") && $request->input("rid") != null){
            DB::table("rm_saved_sections")->insert(['section' => $request->input("section")." alerts",'rm_setting_id'=>$request->input("rid"),'updated_at'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]);
        } else {
            $id = DB::table('rm_save_settings')->insertGetId(["rm_name"=>"front-user","rm_user"=>$memId,"date_added"=>$GLOBALS['currDate']]);
            DB::table("rm_saved_sections")->insert(['section' => $request->input("section")." alerts",'rm_setting_id'=>$id,'updated_at'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]);
        }
        //$data = json_decode($request->getContent(), true);
        
        $data["memId"] = $memId;
        $data["itemID"] = $request->input("itemID");
        $data["section"] = $request->input("section");
        $data["resource"] = $request->input("resourceType");
        $data["action"] = $request->input("action");
        $validator = Validator::make($data, [
            'section' => 'required',
            'memId' => 'int',
            'itemID' => 'required'
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
		//DB::enableQueryLog(); 
        $r = \App\Alert::select('id')
			->where('item_id', $data['itemID'])
            ->where('section', 'like', ''.$data['section'].'%')
           // ->where('section', $data['section'])
           // ->where('status', 'active')
            ->where('memid', $memId);
            //->where('resourceType',$data["resource"]);
			//dd(DB::getQueryLog());
		if ($request->has("priceType") && $request->input("priceType")!='') {
            $r = $r->where('x_days_before',$request->input("priceType"));
        }
        
        if ($request->has("x_days_before") && $request->input("x_days_before")!='') {
            $r = $r->where('x_days_before',$request->input("x_days_before"));
        }
        
		$r = $r->first();
		//dd(DB::getQueryLog());
        if (!empty($r)) {//DB::enableQueryLog(); 
            $alr = \App\Alert::where('id', $r->id);
               if ($request->has("x_days_before") && $request->input("x_days_before")!='') {
                $alr->update(['status' => $data["action"],'x_days_before' =>$request->input("x_days_before"),'updated_on'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]); 
               } else if($request->has("priceType") && $request->input("priceType")!=''){
                $alr->update(['status' => $data["action"],'x_days_before' =>$request->input("priceType"),'updated_on'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]);   
               } else{
                $alr->update(['status' => $data["action"],'updated_on'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]);//dd(DB::getQueryLog());
               }
            calculate_coc($memId);
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => "Record {$data["action"]}d successfully"
                ]
            ]);

        } else {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => "No record found"
                ]
            ]);
        }
    }

    public function addAlerts(Request $request)
    {
        $memId = \App\Helper::getMemId();
        //$data = json_decode($request->getContent(), true);
        
		if($request->has("rid") && $request->input("rid") != null){
            DB::table("rm_saved_sections")->insert(['section' => $request->input("section")." alerts",'rm_setting_id'=>$request->input("rid"),'updated_at'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]);
        } else {
            $id = DB::table('rm_save_settings')->insertGetId(["rm_name"=>"front-user","rm_user"=>$memId,"date_added"=>$GLOBALS['currDate']]);
            DB::table("rm_saved_sections")->insert(['section' => $request->input("section")." alerts",'rm_setting_id'=>$id,'updated_at'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]);
        }
        
        $data["memId"] = $memId;
        $data["itemID"] = $request->input("itemID");
        $data["section"] = $request->input("section");
        $data["xDaysBefore"] = $request->input("xDaysBefore");
        $data["priceType"] = $request->input("priceType");
        $data["eventID"] = $request->input("eventID");
        $data["resource"] = $request->input("resourceType");
        $data["action"] = $request->input("action");
        $validator = Validator::make($data, [
            'section' => 'required',
            'itemID' => 'required',
            'memId' => 'int'
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        $user = new User($data["memId"]);
        ///$isAccessible = $user->isAccessible($data["resource"], $data["section"]);
        $isAccessible = -1;
        if ($isAccessible != -1) {
        //paid + active
            return response()->json([
                'status' => [
                    "code" => 9999,
                    'message' => 'This feature is not accessible to you. Please upgrade your package.'
                ]
            ]);  
        }
		
		$action = 'active';
        if (isset($data['action'])) {
			$action = $data['action'];
        }

	   $xDaysBefore = '';
        if (isset($data['xDaysBefore'])) {
            //$data['xDaysBefore'] = "";
			$xDaysBefore = $data['xDaysBefore'];
        }
        if (isset($data['priceType'])) {
            //$data['xDaysBefore'] = "";
			$xDaysBefore = $data['priceType'];
        }
       /* if ($data['section'] == 'tender' && empty($data['xDaysBefore'])) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::InvalidInputsCode,
                    'message' => 'xDaysBefore only required for section tender'
                ]
            ]);

        } else if ($data['section'] != 'tender' && !empty($data['xDaysBefore'])) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::InvalidInputsCode,
                    'message' => 'xDaysBefore only required for section tender'
                ]
            ]);
        }*/
		//DB::enableQueryLog(); 
        $f = \App\Alert::select('id')->where('item_id', $data['itemID'])
            //->where('section', $data['section'])
            ->where('section', 'like', ''.$data['section'].'%')
            ->where('memid', $memId)
            //->where('resourceType', $data['resource'])
            ;
		
		if($request->has("priceType") && $request->input("priceType")!='')	
			$f = $f->where('x_days_before', $xDaysBefore);
	//dd(DB::getQueryLog());
		/*if ($request->has("priceType") && $request->input("priceType")!='') {
            $f = $f->where('x_days_before',$request->input("priceType"));
        }*/
		$f = $f->first();
			
			/* echo "<pre>";
			print_r($f);
			dd(); */
        //$f = $f->count();
		//dd(DB::getQueryLog());
        //print_r($f);
		if (!empty($f)) {
            $alr = \App\Alert::where('id', $f->id);
               if ($request->has("xDaysBefore") && $request->input("xDaysBefore")!='') {
					$alr->update(
									[
										'x_days_before' =>	$request->input("xDaysBefore"), 
                                        'status' 		=> $action,
                                        'updated_on'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']
									]
								); 
               } else if($request->has("priceType") && $request->input("priceType")!=''){
					$alr->update(
									[
										'x_days_before' =>	$request->input("priceType"), 
                                        'status' 		=>  $action,
                                        'updated_on'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']
                                        
									]
								);     
               }
            calculate_coc($memId);
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => 'Alert Updated Succesfully!'
                ]
            ]);
        }  //DB::enableQueryLog(); 
        \App\Alert::insert([
            'memid' => $memId,
            'section' => $data['section'],
            'item_id' => $data['itemID'],
            'event_id' => $data['eventID']!=''?$data['eventID']:0,
            'resourceType' => $data['resource']!=''?$data['resource']:'',
            'status' => $action,
            'f_date' => $GLOBALS['currDate'],
            'f_time' => $GLOBALS['currTime'],
            'x_days_before' => $xDaysBefore
        ]);  //dd(DB::getQueryLog());
        calculate_coc($memId);
		if($data['section'] == 'price'){
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => 'Alert Set! You will be notified on price change. '
                ]
            ]);
       } else if($data['section'] == 'tender'){
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => 'Awesome! Your alert has been set. '
                ]
            ]);
       } else {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => 'Successfully added to alert'
                ]
            ]);
       }
      
    }
}
