<?php

namespace App\Http\Controllers\v2019;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Rules\Source;
use Validator;
use Session;
use App\Http\Controllers\Auth\User;
use App\Http\Controllers\Auth\authentication;

class Bookmark extends Controller
{

    public function getBookmarkId(Request $request)
    {
        $memId = \App\Helper::getMemId();
		
		if (empty($memId) && $request->has('memid') && $request->input('memid')!=''){
			$memId = $request->input('memid');
		}elseif (empty($memId) && $request->has('accessToken') && $request->input('accessToken')!=''){
			$app_type='SM';
			if ($request->has('app_type') && $request->input('app_type')=='CM')
				$app_type='CM';
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$memId = $auth->authToken($token, $app_type);
		}
		
        //$data = json_decode($request->getContent(), true);
        $data['section'] = $request->input("section");
        $data['memId'] = $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
                ]
            ]);
        }
        //DB::enableQueryLog(); 
        $bookmarkitemIDs = \App\Bookmark::select('item_id')
            ->where('section', $data['section'])
            ->where('memid', $memId)
            ->where('event_id', (isset($data['eventID']) ? $data['eventID'] : 0))
            ->where('status', 'active')
            //->where('resourceType', (isset( $data['resource']) ?  $data['resource'] : ''))
            ->get();
		//dd(DB::getQueryLog()); 
        $val = array();    
        foreach($bookmarkitemIDs as $v ){
           $val[] = $v->item_id;
        }    
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg,
                'input' => $data,
            ],'data' => (!empty($bookmarkitemIDs) ? implode(",",$val) : "")
        ]);
    }

    public function commonRemove(Request $request)
    {
        
       $memId = \App\Helper::getMemId();
        //$data = json_decode($request->getContent(), true);
        $data["memId"] = $memId;
        $data["itemID"] = $request->input("itemID");
        $data["source"] = $request->input("source");
        $data["resource"] = $request->input("resourceType");
        $data["section"] = $request->input("section");
        $data['eventID'] = $request->input("eventID");

        $validator = Validator::make($data, [
            'memId' => 'int',
            'itemID' => 'required',
            //'source' => ['required', new Source],

        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        $tblArray = \App\Helper::tblLists();
        try {
			/* if($data['source'] == "alert")
				$data['source'] = 'tbl_alerts'; */
			
			
			
            if (array_key_exists($data['source'], $tblArray)) {
             //DB::enableQueryLog();
			
                $r = DB::table($tblArray[$data['source']])->select('id');
			
                if($tblArray[$data['source']] == "tbl_bookmarks" || $tblArray[$data['source']] == "tbl_alerts"){
                    if($data["section"] == "speaker")
                       $r = $r->where('item_id', $data['itemID'])->where('section',$data["section"])->where('event_id',$data["eventID"]);
                    else
                       $r = $r->where('item_id', $data['itemID'])->where('section',$data["section"]);
                }
               
                if($tblArray[$data['source']] == "tbl_compare") 
                    $r = $r->where('id', $data['itemID']);
                $r =  $r	->where('memid', $memId)
							//->where('resourceType',(isset( $data['resource'])?$data['resource']:''))
							->first();
            //dd(DB::getQueryLog());
          
                if (!empty($r)) {
                    if($tblArray[$data['source']] == "tbl_bookmarks"){
                       \App\Bookmark::where('id', $r["id"])->delete();
                       return response()->json([
                        'status' => [
                            "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                            'message' => 'Bookmark removed'
                        ]
                    ]);
                    }
                    if($tblArray[$data['source']] == "tbl_compare")
                       \App\Comparision::where('id', $r["id"])->delete();
                     if($tblArray[$data['source']] == "tbl_alerts"){
                       \App\Alert::where('id', $r["id"])->delete();
                       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']]);
                        }
                        
                        calculate_coc($memId);
                        return response()->json([
                            'status' => [
                                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                                'message' => "Alert for this " . $data['section'] .   " has been removed."
                            ]
                        ]);  
                      
                    }   

                    return response()->json([
                        'status' => [
                            "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                            'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg
                        ]
                    ]);
                } else {
                    return response()->json([
                        'status' => [
                            "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                            'message' => "Record already deleted or no record found"
                        ]
                    ]);
                }
            } else {
                return response()->json([
                    'status' => [
                        "code" => \App\RestApiResponseCodes::somethingWentWrongCode,
                        'message' => \App\RestApiResponseCodes::somethingWentWrongMsg,
                    ]
                ]);
            }
        } catch (\Exception $ex) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::somethingWentWrongCode,
                    'message' => \App\RestApiResponseCodes::somethingWentWrongMsg,
                ]
            ]);
        }

    }

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

        $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
                ]
            ]);
        }
        $f = \App\Bookmark::where('item_id', $data['itemID'])
            ->where('section', $data['section'])
            ->where('memid', $memId)
            ->where('status', 'active')
          //  ->where('resourceType',(isset($data['resource'])?$data['resource']:''))
            ->count();
        if ($f) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => 'Bookmark already exists'
                ]
            ]);
        }

        \App\Bookmark::insert([
            'memid' => $memId,
            'section' => $data['section'],
            'item_id' => $data['itemID'],
            'event_id' => (isset($data['eventID'])?$data['eventID']:0),
            'status' => 'active',
            //'resourceType' => (isset($data['resource'])?$data['resource']:''),
            'f_date' => date("Y-m-d"),
            'f_time' => date("h:i:s"),
        ]);
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => 'Bookmark Added'
            ]
        ]);
    }
}
