<?php
// NEW FOR FANTASY TRIVIA QUESTIONS
class questionsModel extends baseModel {

	public $tableName = 'api_challenges';
	
	static public $fields = [
		'id',
		'ttype',
		'is_active',
		'cat_id',
		'title',
		'shorttitle',
		'description',
		'diff',
		'featured',
		'itemtitles',
		'itemChoices',
		'date',
		'itemdescrips',
		'audio',
		'video',
		'images',
		'featured',
		'sort',
		'allChoices',
		'parent',
		'qty',
		'pid',
		'ans',
		'cost',
		'win',
		'bud',
		'budleft',
		'gamewithinthegame',
		'itemMaster',
		'sched',
		'tags',
		'answers',
		'schedules',
		'sleep',
		'done'
	];
	
	function fetchSeries(&$series){
		
		//		echo $series['id'];
		//		exit;
		
		//$this->db->where('project_id = ?', $series['id']);
		$this->db->where('id = ?', $series['id']);
		$this->db->order_by('sort ASC');
		$series['backing'] = $this->db->select('backing'); // Line 343 below is the Edit function
		
//		echo "<pre>";
//		print_r($series['backing']);
//		exit;

		foreach ($series['backing'] as $i => $requirement) {
			if (!empty($requirement['cf_id'])) {
				//$this->db->where('id = ?', $requirement['cf_id']);
				//$series['backing'][$i]['user'] = $this->db->select('users',['name','first_name','user_slug','image'])[0];
			}
		}
//		echo "<pre>";
//		print_r($series);
//		exit;

	}
	
	function get($id = 0){
		global $website_options;

		if (!is_numeric($id)) {
			return -1;
		}
		$this->db->where('id = ?', $id);
		$series = $this->db->select('api_challenges')[0];

		if ($series)
			$this->fetchSeries($series);

		return $series;
	}

	function getList($cond = []) {
		if (isset($cond['user_id'])) {
			$this->db->where("user_id = ?", $cond['user_id']);
		}
		
		if (isset($cond['parent'])) {
			$this->db->where("parent = ?", $cond['parent']);
		}
		
		if (isset($cond['cat_id'])) {
			$this->db->where("cat_id = ?", $cond['cat_id']);
		}
		
		if (isset($cond['sched'])) {
			$this->db->where("sched = ?", 1);
		}
		
		if (isset($cond['pid'])) {
			$this->db->where("pid = ?", $cond['pid']);
		}
		
		if (isset($cond['bydate'])) {
			$this->db->order_by("scheduled DESC");
		}		
		
		//$this->db->where('parent = ?', 1);
		$series = $this->db->select('api_challenges');
		return $series;
	}
	
	function getChallenges($cond = []){
		if (isset($cond['user_id'])) {
			$this->db->where("user_id = ?", $cond['user_id']);
		}

		if (isset($cond['parent'])) {
			$this->db->where("parent = ?", $cond['parent']);
		}

		if (isset($cond['cat_id'])) {
			$this->db->where("cat_id = ?", $cond['cat_id']);
		}

		if (isset($cond['sched'])) {
			$this->db->where("sched = ?", 1);
		}

		if (isset($cond['pid'])) {
			$this->db->where("pid = ?", $cond['pid']);
		}

		if (isset($cond['bydate'])) {
			$this->db->order_by("scheduled DESC");
		}

		//$this->db->where('parent = ?', 1);
		$this->db->order_by("featured ASC");
		$series = $this->db->select('api_challenges');
		return $series;
	}	
	
	function insert($data){
//		[project_type_id] => 2
//		[ttype] => 1
//		[cat_id] =>
//		[title] =>
//		[description] =>
//		[qty] =>
//		[locspec] => 0
//		echo "<pre>";
//		print_r($data);
//		exit;
		//$update_data = $data;

//				echo "<pre>";
//				print_r($data);
//				exit;

//		foreach ($update_data as $index => $value) {
//			if (!in_array($index, self::$fields)) {
//				unset($update_data[$index]);
//			}
//		}
		//$rmdate = strtotime($data['remindme']);

		//$data['remindme'] = date('Y-m-d H:i:s', $rmdate);

		$this->db->insert('api_challenges', $data);
		return $this->db->insert_id();
	}

	function update($id, $data) {
		// a;aa;aye;hey|b;bb;bee;be;p;pea;pee|c;cc;see;sea|d;dd;dee;dea;the
		
//		if (isset($_FILES['images']) && !$_FILES['images']['error']) {
//			$cur_image = $this->db->select_one("messagesout", ['images']);
//
//			if (!empty($cur_image['images']) && isset($_FILES['images']) && !$_FILES['images']['error']) {
//				@unlink($cur_image['images']);
//			}
//
//			$file = $_FILES['images'];
//
//			if (!empty($_SERVER['SERVER_NAME'])) {
//				$site_root = $_SERVER['SERVER_NAME'];
//			} else {
//				$site_root = $_SERVER['HTTP_HOST'];
//			}
//
//			if ($ext == 'jpg' || $ext == 'png' || $ext = 'jpeg' || $ext = 'gif' ) {
//				$imgname = strtolower(basename($_FILES["images"]["name"]));
//				//$destination = "static/uploads/notifications/$imgname";
//				$destination = "static/collections/video/$imgname";
//				//$fullpath = "https://" . $site_root . "/static/uploads/notifications/$imgname";
//				$fullpath = "https://" . $site_root . "/static/collections/video/$imgname";
//				move_uploaded_file($file['tmp_name'], $destination);
//				$this->db->where('id=?', $id);
//				$this->db->update('api_challenges', ['images' => $imgname]);
//			}
//		}

		if ($data['parent']==1) {
			$questioninfo = [];
			$questioninfo['title'] = $data['title'];
			$questioninfo['description'] = $data['description'];
//			$questions = 
			$this->updateAllQuestions($id, $questioninfo);
			//$this->db->where('id=?', $id);
			//$this->db->update('api_challenges', $data);
		}

		// VIDEO
		if (isset($_FILES['video']) && !$_FILES['video']['error']) {
			$this->db->where('id=?', $id);
			$cur_video = $this->db->select_one("api_challenges", ['video']);

			if (!empty($cur_video['video']) && isset($_FILES['video']) && !$_FILES['video']['error']) {
				@unlink($cur_video['video']);
			}

			$file = $_FILES['video'];

			if (!empty($_SERVER['SERVER_NAME'])) {
				$site_root = $_SERVER['SERVER_NAME'];
			} else {
				$site_root = $_SERVER['HTTP_HOST'];
			}

			if ($ext == 'jpg' || $ext == 'png' || $ext = 'jpeg' || $ext = 'gif' ) {
				$imgname = strtolower(basename($_FILES["video"]["name"]));
				//$destination = "static/uploads/notifications/$imgname";
				$destination = "static/collections/video/$imgname";
				//$fullpath = "https://" . $site_root . "/static/uploads/notifications/$imgname";
				$fullpath = "https://" . $site_root . "/static/collections/video/$imgname";
				move_uploaded_file($file['tmp_name'], $destination);
				$this->db->where('id=?', $id);
				$this->db->update('api_challenges', ['video' => $imgname]);
			}
		}			
		
		if ($data['ans'] == "A") {
			$data['itemMaster'] = "a;aa;aye;hey";
		} elseif ($data['ans'] == "B") {
			$data['itemMaster'] = "b;bb;bee;be;p;pea;pee";
		} elseif ($data['ans'] == "C") {
			$data['itemMaster'] = "c;cc;see;sea";
		} elseif ($data['ans'] == "D") {
			$data['itemMaster'] = "d;dd;dee;dea;the";
		} else {
			$data['itemMaster'] = "";
		}
		
		$this->db->where('id=?', $id);
		$this->db->update('api_challenges', $data);
	}	
	
	function uploadVideo($id, $data){
		// VIDEO
		if (isset($_FILES['video']) && !$_FILES['video']['error']) {
//			$this->db->where('id=?', $id);
//			$cur_video = $this->db->select_one("api_challenges", ['video']);
//
//			if (!empty($cur_video['video']) && isset($_FILES['video']) && !$_FILES['video']['error']) {
//				@unlink($cur_video['video']);
//			}

			$file = $_FILES['video'];

			if (!empty($_SERVER['SERVER_NAME'])) {
				$site_root = $_SERVER['SERVER_NAME'];
			} else {
				$site_root = $_SERVER['HTTP_HOST'];
			}

			if ($ext == 'jpg' || $ext == 'png' || $ext = 'jpeg' || $ext = 'gif' ) {
				$imgname = strtolower(basename($_FILES["video"]["name"]));
				//$destination = "static/uploads/notifications/$imgname";
				$destination = "static/collections/video/$imgname";
				//$fullpath = "https://" . $site_root . "/static/uploads/notifications/$imgname";
				$fullpath = "https://" . $site_root . "/static/collections/video/$imgname";
				move_uploaded_file($file['tmp_name'], $destination);
				$this->db->where('id=?', $id);
				$this->db->update('api_challenges', ['video' => $imgname]);
				echo 'ok';
			}
		}

//		$this->db->where('id=?', $id);
//		$this->db->update('api_challenges', $data);
	}
	
	function uploadImage($id, $data){
		// IMAGE
		if (isset($_FILES['images']) && !$_FILES['images']['error']) {

			$file = $_FILES['images'];

			if (!empty($_SERVER['SERVER_NAME'])) {
				$site_root = $_SERVER['SERVER_NAME'];
			} else {
				$site_root = $_SERVER['HTTP_HOST'];
			}

			if ($ext == 'jpg' || $ext == 'png' || $ext = 'jpeg') {
				$imgname = strtolower(basename($_FILES["images"]["name"]));
				//$destination = "static/uploads/notifications/$imgname";
				$destination = "static/collections/$imgname";
				//$fullpath = "https://" . $site_root . "/static/uploads/notifications/$imgname";
				$fullpath = "https://" . $site_root . "/static/collections/$imgname";
				move_uploaded_file($file['tmp_name'], $destination);
				$this->db->where('id=?', $id);
				$this->db->update('api_challenges', ['images' => $imgname]);
				echo 'ok';
			}
		}
	}

	function delete($id) {
		$this->db->where('id=?', $id);
		$this->db->delete('api_challenges');
	}
	
	function deleteSet($id){
		$this->db->where('pid=?', $id);
		$seriesQuestionIDs = $this->db->select('api_challenges','id');
		
//		print_r($seriesQuestionIDs);
//		exit;
		
//		if (count($seriesQuestionIDs) < 1) {
//			return 1;
//		}
		
		if ($seriesQuestionIDs) {
			foreach ($seriesQuestionIDs as $seriesQuestionID) {
				//print_r($seriesQuestion);
				//echo $seriesQuestionID['id'] . "<br />";
				$this->db->where('id=?', $seriesQuestionID['id']);
				$this->db->delete('api_challenges');
				//echo $seriesQuestion['id'] . "<br />";
				//echo $series_id['id'] . "<br />";
			}
		}
	
	}

	function getItem($id) {
		$this->db->where('id=?', $id);
		
		$series = $this->db->select('api_challenges')[0];
		
		if (!empty($series)) {
			$this->db->where('pid=?', $series['id']);
			$series['questionids'] = $this->db->select('api_challenges','id');

			//print_r($series['questionids']);

			return $series;	
		} else {
			return 0;
		}

	}
	
	function updateAllQuestions($id, $updates){
		//print_r($id);
		$this->db->where("pid = ?", $id);
		$question_ids = $this->db->select('api_challenges','id');
		
		foreach ($question_ids as $question_id) {
			//echo $question_id['id'] ."<br />";
			$this->db->where("id = ?", $question_id['id']);
			$this->db->update("api_challenges", [
				'title'		   => $updates['title'],
				'description'  => $updates['description']
			]);
		}
		
		//print_r($question_ids);
		
		//print_r($updates);
//		$this->db->where("pid = ?", $id);
//		
//		foreach ($updates as $update) {
//			// project_talents entry
//			$this->db->where("pid = ?", $id);
//			echo $update['title'] . "<br />";
////			$this->db->update("api_challenges", [
////				'title'		   => $update['title'],
////				'description'  => $update['description']
////			]);
//		}
	}
	
	//////////////////////////////////////////////////////////////////////
	// TRIVIA FUNCTIONS
	//////////////////////////////////////////////////////////////////////
	
	// ORIGINAL - NOT USED ANY MORE
	function getQuestionIDs(){
		//$this->db->where("pid = ?", $id);
		$questionIds = $this->db->select('api_challenges','id');
		return $questionIds;
	}
	// NEW, REMOVES SHOWN CHALLENGES/QUESTIONS FROM WHAT WE SHOW THE USER(S), THEN SHOWN, BUT NOT ANSWERED
	function getfreshChallengeIDs($uid){
		$allIDs = [];
		$this->db->where("sched = ?", 0);
		$this->db->where("is_active = ?", 1);
		$this->db->where('answers < 10');
		$allChallenges = $this->db->select('api_challenges');
		foreach ($allChallenges as $allChallenge) {
			$allIDs[] = $allChallenge['id'];
		}

		$shownIDs = [];
		$this->db->where("user_id = ?", $uid);
		$this->db->group_by("ch_id");
		$shownChallenges = $this->db->select('api_shown');
		foreach ($shownChallenges as $shownChallenge) {
			$shownIDs[] = $shownChallenge['ch_id'];
		}

		$freshIDs = array_diff($allIDs,$shownIDs);
		//return $freshIDs;
			
		if (!empty($freshIDs)) {
//			echo "Fresh: " . $freshIDs;
//			exit;
			return $freshIDs;	
		} else {
//			echo "No fresh Challenges";
//			exit;
			$notAnswered = [];
			// IF THERE ARE NO FRESH ONES, THEN SHOW SHOWN, BUT NOT ANSWERED
			$this->db->where("user_id = ?", $uid);
			$this->db->where("q = ?", 0);
			$this->db->group_by("ch_id");
			$shownbutnotansweredChallenges = $this->db->select('api_shown');
//			return $shownbutnotansweredChallenges;
//			exit;
//			$i = 1;
			foreach ($shownbutnotansweredChallenges as $shownbutnotansweredChallenge) {
//				echo $i . ") " . $shownbutnotansweredChallenge['ch_id'] . "<br />";
//				$i++;
				$notAnswered[] = $shownbutnotansweredChallenge['ch_id'];
			}

			if (!empty($notAnswered)) {
				return $notAnswered;
			} else {
				return 0;
			}
		}

		//return $allIDs;
		//return $shownIDs;
		//return $allChallenges;
		//return $shownChallenges;
	}
	
	function getfreshChallengeIDsbyIP($userip){
		$allIDs = [];
		$this->db->where("sched = ?", 0);
		$this->db->where("is_active = ?", 1);
		$this->db->where('answers < 10');
		$allChallenges = $this->db->select('api_challenges');

		foreach ($allChallenges as $allChallenge) {
			$allIDs[] = $allChallenge['id'];
		}
		//return $allIDs;
		//exit;
		
		$shownIDs = [];
		$this->db->where("user_ip = ?", $userip);
		$this->db->group_by("ch_id");
		$shownChallenges = $this->db->select('api_shown');
//		return $shownChallenges;
//		exit;
		
		foreach ($shownChallenges as $shownChallenge) {
			$shownIDs[] = $shownChallenge['ch_id'];
		}
//		return $shownIDs;
//		exit;
		$freshIDs = array_diff($allIDs,$shownIDs);
		if (!empty($freshIDs)) {
			return $freshIDs;	
		} else {
			// NO MORE FRESH CHALLENGES, SO LET'S SHOW SHOWN, BUT NOT ANSWERED
			//return 0;
			$notAnswered = [];
			$this->db->where("user_ip = ?", $userip);
			$this->db->where("q = ?", 0);
			$this->db->group_by("ch_id");
			$shownbutnotansweredChallenges = $this->db->select('api_shown');

			foreach ($shownbutnotansweredChallenges as $shownbutnotansweredChallenge) {
				$notAnswered[] = $shownbutnotansweredChallenge['ch_id'];
			}
			return $notAnswered;
			exit;

			if (!empty($notAnswered)) {
				return $notAnswered;	
			} else {
				return 0;
			}
		}
	}
	
	function checkShown($uid,$cid){
		$this->db->where("user_id = ?", $uid);
		$this->db->where("ch_id = ?", $cid);
		$challengeLog = $this->db->select('api_shown');

		//print_r($challenge);
		if (!empty($challengeLog)) {
			return 1; // it already has been shown
		} else {
			return 0; // it hasn't been shown
		}
	}
	function checkShownbyIP($userip, $cid){
		$this->db->where("user_ip = ?", $userip);
		$this->db->where("ch_id = ?", $cid);
		$challengeLog = $this->db->select('api_shown');

		//print_r($challenge);
		if (!empty($challengeLog)) {
			return 1; // it already has been shown
		} else {
			return 0; // it hasn't been shown
		}		
	}
	
	// cat_id is there, but unused - create a toggle list for this
	// use shorttitle
	// 1 Question | re: The Current NBA | (Difficulty: 7/10) |
	// Cost to Play: $0.10 to Win $0.20 + a share of $500
	function getrandomChallenge($id){
		$this->db->where("id = ?", $id);
		$this->db->where("sched = ?", 0);
		$this->db->where("is_active = ?", 1);
		$this->db->where('answers < 10');
		$challenge = $this->db->select('api_challenges','id,title,shorttitle,cost,win,diff,gamewithinthegame,sched,scheduled,images');
		//$challenge = $this->db->select('api_challenges');
		return $challenge;
	}
	
	function getsponsoredChallenge($id){
		$this->db->where("id = ?", $id);
		$this->db->where("sched = ?", 1);
		//$this->db->where("is_active = ?", 1);
		$challenge = $this->db->select('api_challenges','id,title,shorttitle,cost,win,diff,gamewithinthegame,sched,scheduled,images');
		//$challenge = $this->db->select('api_challenges');
		return $challenge;
	}
	
	function getrandomQuestion($id){
		$this->db->where("id = ?", $id);
		$question = $this->db->select('api_challenges');
		return $question;
	}
	
	function getChallenge($id){
		$this->db->where("id = ?", $id);
		$challenge = $this->db->select_one('api_challenges');
		return $challenge;
	}
	
	function checkTheAnswer($challengeID, $ansID){
		$this->db->where("id = ?", $challengeID);
		$question = $this->db->select('api_challenges');
		
		if (!empty($question)) {
			return $question;
			//return $question[0]['ans'];
		}
		//return $question;
	}
	
	function saveSkippedChID($cid, $uid){
		$this->db->where("user_id = ?", $uid);
		$this->db->where("ch_id = ?", $cid);
		$this->db->order_by('date ASC');
		$challengeLog = $this->db->select_one('api_shown');
		
		$skipdate = date("Y-m-d H:i:s");
		
		//print_r($challenge);
		if (!empty($challengeLog)) {
			//return $challengeLog[0]['id'];
			$this->db->where('id=?', $challengeLog['id']);
			$this->db->update('api_shown', ['skip' => 1,'skipdate' => $skipdate]);	
		}
	}
	
	function saveQShown($cid, $uid){
		// Deduct the cost first from the user's virtual_balance
		//$this->db->where("id = ?", $uid);
		//$this->db->update('users', ['virtual_balance' => 1,'qdate' => $qdate]);
		
		// NOW, SAVE THE QUESTION BEING SHOWN IN THE SHOWN TABLE
		$this->db->where("user_id = ?", $uid);
		$this->db->where("ch_id = ?", $cid);
		$challengeLog = $this->db->select('api_shown');

		$qdate = date("Y-m-d H:i:s");

		//print_r($challenge);
		if (!empty($challengeLog)) {
			//return $challengeLog[0]['id'];
			$this->db->where('id=?', $challengeLog[0]['id']);
			$this->db->update('api_shown', ['q' => 1,'qdate' => $qdate]);
		} else {
			// Let's insert it
			$this->db->insert("api_shown", [
				'user_id' => $uid,
				'user_ip' => $_SERVER['REMOTE_ADDR'],
				'ch_id' => $cid,
				'date'  => date("Y-m-d H:i:s")
			]);
		}
	}
	
	function saveAnswer($cid, $uid, $choice, $correctness){
		$this->db->where("user_id = ?", $uid);
		$this->db->where("ch_id = ?", $cid);
		$challengeLog = $this->db->select('api_shown');

		//print_r($challenge);
		if (!empty($challengeLog)) {
			//return $challengeLog[0]['id'];
			$this->db->where('id=?', $challengeLog[0]['id']);
			$this->db->update('api_shown', ['ans' => $choice, 'correct' => $correctness]);
		} 
	}
	
	function saveAnswerandTime($cid, $uid, $choice, $correctness, $time){
		$this->db->where("user_id = ?", $uid);
		$this->db->where("ch_id = ?", $cid);
		$challengeLog = $this->db->select('api_shown');

		//print_r($challenge);
		if (!empty($challengeLog)) {
			//return $challengeLog[0]['id'];
			$this->db->where('id=?', $challengeLog[0]['id']);
			$this->db->update('api_shown', ['ans' => $choice, 'correct' => $correctness, 'time' => $time]);
		}
	}
	
	// CHECK TO SEE IF IT'S A NON-SCHED CHALLENGE
	function checkSched($id){
		$this->db->where("id = ?", $id);
		$this->db->where("sched = ?", 1);
		$question = $this->db->select('api_challenges');
		if (!empty($question)) {
			return 1; // is sched	
		} else {
			return 0; // is NOT sched, so we block these from being directly accessed
		}
	}	
	
	function addaViewNew($id, $userip, $section){
		
		if ($id == "https://fantasytrivia.com/profile/unreadMessagesCount" || $id == "https://fantasytrivia.com/profile/unreadNotificationsCount" || $id == "/auth/view" || $id == "https://fantasytrivia.com/auth/view") {
			return;
		}
		
		date_default_timezone_set('CDT');
		date_default_timezone_set('America/Chicago');
		$timenow = date('Y-m-d H:i:s');
		
        $this->db->insert("pageviews", [
            'page' => $id,
            'userip' => $userip,
            'section' => $section,
            'date' => $timenow
        ]);
    }
    
	function getTotalUniqueViews($section, $id){
		$last5 = date('Y-m-d H:i:s',time()-300);
		
		$this->db->where('section=?', $section);
        $this->db->where('page=?', $id);
		$this->db->where("date > '$last5'");
		//$this->db->where("(date > '.$last5.')");
		//$this->db->where('date > 15:36:53');
		//query("UPDATE square_users SET square_id='$square_id' WHERE token='$token'");
        
        return $this->db->select('pageviews', 'COUNT(DISTINCT(userip)) AS c')[0][c];
    }  
    
    function getTotalOnline(){
		$last5 = date('Y-m-d H:i:s',time()-300);
		$this->db->where("date > '$last5'");

		return $this->db->select('pageviews', 'COUNT(DISTINCT(userip)) AS c')[0][c];   	
    } 
        
    function getTotalPageViews($section, $id) {
		$this->db->where('section=?', $section);
        $this->db->where('page=?', $id);
        return $this->db->select('pageviews', 'COUNT(page) AS c')[0][c];
    }    
    
	function getChallengesbyAccount($cond = []){
		//var_dump($cond);
		if (isset($cond['tags'])) {
			$this->db->where("tags = ?", $cond['tags']);
		}
		//$this->db->where('parent = ?', 1);
		$this->db->order_by("featured ASC");
		$challenges = $this->db->select('api_challenges');
		return $challenges;
	}
	function updateCount($challengeID){
		$this->db->query("UPDATE api_challenges SET answers=answers+1 WHERE id='$challengeID'");
	}
	
	function checkRSVP($userID,$challengeID){
		$this->db->where('user_id=?', $userID);
		$this->db->where('ch_id=?', $challengeID);
		$this->db->where('paid=?', 1);
		$shownRecord = $this->db->select_one('api_shown');
		//return $shownRecord;
		if (!empty($shownRecord)) {
			return 1;
		} else {
			return 0;
		}
	}
	
	function getRSVP($userID, $challengeID){
		$this->db->where('user_id=?', $userID);
		$this->db->where('ch_id=?', $challengeID);
		$shownRecord = $this->db->select_one('api_shown');
		if (!empty($shownRecord)) {
			return $shownRecord;	
		}
	}
	
	function makeRSVP($userID, $challengeID){
		$this->db->where('user_id=?', $userID);
		$this->db->where('ch_id=?', $challengeID);
		$confirmRSVP = $this->db->update('api_shown', ['paid' => 1]);
		return $confirmRSVP;
	}
	
	function unRSVP($userID, $challengeID){
		$this->db->where('user_id=?', $userID);
		$this->db->where('ch_id=?', $challengeID);
		$confirmRSVP = $this->db->update('api_shown', ['paid' => 0]);
		return $confirmRSVP;
	}
	
	function countAnswers(){
		
	}
}