<?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;

class notifyController extends Controller
{

    public function getNotification(Request $request)
    {
        $memId = \App\Helper::getMemId();
        //$data = json_decode($request->getContent(), true);

        $data["memId"] = $memId;
        $data["resource"] = $request->input("resourceType");

        $validator = Validator::make($data, [
            'memId' => 'int'
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
		
		//$days_ago = date('Y-m-d', strtotime('-3 days', strtotime(date("Y-m-d"))));
		$days_ago = date('Y-m-d', strtotime(date("Y-m-d")));
        $notify_id = \App\Notify::select("notification_status","sms_status", "notification_active_for")
            ->where('memid', $memId)
            ->where('resourceType',$data["resource"])
            //->where('f_date', '>=', $days_ago)
            ->get();

		
        $stat = "inactive";    
        $stat_sms = "inactive";    
		$notification_type=array("Insights","Intel", "Price Alerts", "Tender Alerts");
		$notificationArr=[];
        foreach($notify_id as $v ){
            $stat = $v->notification_status;
            $stat_sms = $v->sms_status;
            $notification_active_for = explode(',',$v->notification_active_for);
			
			foreach($notification_type as $key=>$keyValue){
				$notificationArr[$key]['title'] = $keyValue;
				if(in_array($keyValue, $notification_active_for)!==false){
					$notificationArr[$key]['active'] = 1;					
				}else{
					$notificationArr[$key]['active'] = 0;
				}
				
				$notificationArr[$key]['image'] = "https://www.steelmint.com/nw/public/images/appIcon/".str_replace(" ","_",$keyValue).".png";
			}
        }
		
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => "success",
                //'smsStatus'=>(!empty($stat_sms)) ? $stat_sms : "active",
                //'pushStatus'=>(!empty($stat)) ? $stat : "active"
                'smsStatus'=>$stat_sms,
                'pushStatus'=>$stat,
                'pushStatusImage'=>"https://www.steelmint.com/nw/public/images/appIcon/Notifications.png",
                'pushType'=>$notificationArr
            ]
        ]);
    }

    public function addNotification(Request $request)
    {
        $memId = \App\Helper::getMemId();
        //$data = json_decode($request->getContent(), true);
        $ide = 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")."notifications-app",'rm_setting_id'=>$ide,'updated_at'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]);
         
         $data["memId"] = $memId;
        $data["resource"] = $request->input("resourceType");
        $validator = Validator::make($data, [
            'memId' => 'int'
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
      
		 
        $f = \App\Notify::select('id')->where('memid', $memId)->where('resourceType', $data['resource']);
		$f = $f->first();
        //$f = $f->count();
		
        //print_r($f);
		if (!empty($f)) {//DB::enableQueryLog();
            $alr = \App\Notify::where('id', $f->id);
               if ($request->has("pushNotification") && $request->input("pushNotification")!='') {
				   $notification_active_for = $request->has("pushNotificationType")?$request->input("pushNotificationType"):'';
				   
					$alr->update(['notification_status' => $request->input("pushNotification"),'notification_active_for' => $notification_active_for,'updated_on'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]); 
               } //dd(DB::getQueryLog()); 
               if ($request->has("sms") && $request->input("sms")!='') {
                $alr->update(['sms_status' => $request->input("sms"),'updated_on'=>$GLOBALS['currDate']." ".$GLOBALS['currTime']]); 
               }
            calculate_coc($memId);
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => 'Notification updated successfully!'
                ]
            ]);
        } 

        \App\Notify::insert([
            'memid' => $memId,
            'resourceType' => $data['resource']!=''?$data['resource']:'',
            'notification_status' => $request->has("pushNotification") && $request->input("pushNotification")!=''?'active':'inactive',
            'sms_status' => $request->has("sms") && $request->input("sms")!=''?'active':'inactive',
            'f_date' => $GLOBALS['currDate'],
            'f_time' => $GLOBALS['currTime']
        ]);  //dd(DB::getQueryLog());
        calculate_coc($memId);
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => 'Notification added successfully'
            ]
        ]);
      
    }

}
