<?php
// THIS CONTROLS THE HOST CHALLENGES
class BlogController extends baseController
{
    function index(){
        global $website_options;

        $id = $this->registry->args[1];
		if (!is_numeric($id)) {
			header("Location: /challenges/all");
            exit;
        }
        if ($this->registry->args[2] == 'edit') {
        	$this->edit();
        }

		$challengesModel = new challengesModel();
		$userModel    = new userModel();
		$commentModel = new commentModel();
		
		$project = $challengesModel->get($id);
//		print_r($project);
//		exit;
		
		$project['buyerrating'] = $challengesModel->getBuyerRating($id);
		//		echo "Buyer Rating: ";
		//		print_r($project['buyerrating']);
		$project['sellerrating'] = $challengesModel->getSellerRating($id);
        
		if ($_POST) {
			if ($_POST['submit_rating'] && !empty($_POST['submit_rating'])) {
//				print_r($_POST);
//				exit;
//				date_default_timezone_set('CDT');
//				date_default_timezone_set('America/Chicago');
//				date_default_timezone_get();
				//$now_time = date('Y-m-d H:i:s');
				//$cst_time = date('-5 hours', strtotime($now_time));
				//$_POST['timestamp'] = date("Y-m-d H:i:s", strtotime("-5 hours"));
				$_POST['timestamp'] = date('Y-m-d H:i:s');
//				echo $_POST['timestamp'];
//				exit;
				//$_POST['timestamp'] = $cst_time;
				$_POST['rating'] = $_POST['submit_rating'];

				if ($_POST['usertype']=="seller" && !empty($project['sellerrating'])) {
					//echo "You've already submitted a rating.";
					header("Location: /challenge/$id?msg=AlreadyLeftRating");
					exit;
				}
				
				if ($_POST['usertype']=="buyer" && !empty($project['buyerrating'])) {
					//echo "You've already submitted a rating.";
					header("Location: /challenge/$id?msg=AlreadyLeftRating");
					exit;
				}
				
				//echo "Yep, rate it...<br />";
				//echo $_POST['submit_rating'];
//				review_id
//				project_id
//				user_id
//				review
//				submit_rating
//				echo $_POST['usertype'];
//				exit;
				//$r = $challengesModel->submitRating($_POST['submit_rating'], $_POST['review_id']);
//				if ($_POST['usertype'] = "seller") {
//					$challengesModel->submitProposalRating($_POST);
//				}
//				echo "<pre>";
//				print_r($_POST);
//				echo "<br/>";
				$ratingStatus = $challengesModel->submitRating($_POST);
				
				if ($_POST['usertype']=="seller") {
					if (!empty($project['buyerrating'])){
						$challengesModel->setProjectStatus($id, 'withdrawn');
						$challengesModel->setProposalStatus($_POST['review_id'], 5);
					}
					header("Location: /challenge/$id?msg=thxrating1");
					exit;	
				}
				if ($_POST['usertype']=="buyer") {
					if (!empty($project['sellerrating'])){
						$challengesModel->setProjectStatus($id, 'withdrawn');
						$challengesModel->setProposalStatus($_POST['review_id'], 5);	
					}
					header("Location: /challenge/$id?msg=thxrating2");
					exit;
				}				
				exit;
				//echo $ratingStatus;
			}
//			else {
//				header("Location: /challenge/$id?msg=empty");
//				exit;
//			}		 
            if ($_POST['unlock-review'] && is_numeric($_POST['unlock-review'])) {
                $r = $challengesModel->unlockReview($_POST['unlock-review']);
                echo json_encode($r);
                exit;  
            }
			if ($_SESSION['loggedin'] && $_POST['reward']) {
				$challengesModel->submitReq($_POST);
				header("Location: /challenge/$id");
				exit;
			}
            if ($_SESSION['loggedin'] && $_POST['content']) {
                //$challengesModel->submitReview($_POST, $id);
				//print_r($_POST);
				//exit;
				//$comment_id = $challengesModel->postComment($_POST);
				//echo $comment_id;
				$challengesModel->postComment($_POST);
            }		
            if ($_SESSION['loggedin'] && $_POST['proposal']) {
                $challengesModel->submitProposal($_POST, $_FILES, $id);

				// LET'S SEND AN EMAIL NOTIFICATION
				$this->sendProposalNotification($project['user']['email'], $project['user']['ver_code']);
				
				// LET'S SEND A TEXT MESSAGE NOTIFICATION
				require "3rdparty/twilio-php-master/Services/Twilio.php";

				$AccountSid = "ACc33ee9aa71e9a841111c0f6ef976af61";
				$AuthToken = "774b5173cc5c1ba2b61ee20769888fa1";

				$client = new Services_Twilio($AccountSid, $AuthToken);
				try {
					$message = $client->account->messages->create(array(
					"From" => "312-878-9582",
					"To" => $project['user']['phone'],
					"Body" => "A new player just joined your Challenge! Visit https://voicetrivia.com/challenge/".$id." to view it. To unsubscribe to these notifications, visit https://voicetrivia.com/unsubscribe/".$project['user']['ver_code'],
					));
				} catch (\Exception $e) {
					//return $e->getMessage();
				}

				header("Location: /challenge/$id?msg=proposal");
            	exit;
            }
        }
        
		if (isset($_GET['ok'])) {
			$msg='';
			unset($msg);
			header("Location: /challenge/$id");
			//header("Location: /");
			exit;
		}
        
		if (isset($_GET['comment'])) {
			//			header("Location: /contact");
			//			exit;
			if (isset($_GET['delete'])) {
				//				header("Location: /about");
				//				exit;
				$comment_id = $_GET['delete'];
				$commentModel->delete($comment_id);
			}
			header("Location: /challenge/$id");
			exit;
			//echo $comment_id;
		}
        
        $typesModel = new typesModel();
        $types = $typesModel->getList();
//		echo "<pre>";
//		print_r($types);
//		exit;

//        $talentModel = new talentModel();
//        $skills = $talentModel->getList();  

    	//$project = $challengesModel->get($id);
        //$project['reviews'] = $challengesModel->getReviews($id);
		$project['proposals'] = $challengesModel->getProposals($id);
		$project['candidate'] = $challengesModel->getHiredCandidate($id); // selected offer
		$project['selectedoffer'] = $challengesModel->getHiredProposal($id);
		//print_r($project['selectedoffer']);
        
        // PAGEVIEW COUNTER 
        $userip = $_SERVER['REMOTE_ADDR'];
		$challengesModel->addaView($id,$userip);
		$uniqueviews = $challengesModel->getTotalUniqueViews($id);
		$pageviews = $challengesModel->getTotalPageViews($id);   

		if ($_SESSION['user']['id']) {
			$project['joinStatus'] = $challengesModel->checkStatus($_SESSION['user']['id'],$id);
            //$project['my_disputes']  = $challengesModel->getDisputes(['project_id' => $id, 'user_id' => $_SESSION['user_id']]);
            $his_id = $_SESSION['user_id'] == $project['user_id'] ? $project['candidate']['id'] : $project['user_id'];
			$project['his_disputes'] = $challengesModel->getDisputes(['project_id' => $id, 'user_id' => $his_id]);

			$my_proposal = $challengesModel->getProposals($project['id'], $_SESSION['user']['id'])[0];
        }

        if ($project['is_private']
            && (empty($_SESSION['user']['id'])
                || ($project['user_id'] != $_SESSION['user_id']
				&& $challengesModel->getInviteState($project['id'], $_SESSION['user_id']) == -1)))
        {
            // current user is not allowed in this project. (Invite only, private project)
            header("Location: /category/all");
            exit;
        }

//        if ($_SESSION['loggedin']) {
//            $project['unlocked_reviews'] = $challengesModel->getUnlockedReviews($id);
//
//            // Remove unlocked reviews from main reviews array
//            foreach ($project['unlocked_reviews'] as $unlocked_review) {
//                foreach ($project['reviews'] as $index => $review) {
//                    if ($review['review_id'] == $unlocked_review['review_id']) {
//                        unset($project['reviews'][$index]);
//                    }
//                }
//            }
//        }

       // $project['recent_reviewers'] = $challengesModel->getRecentReviewers($id);
        $meta_title = $project['title'] . ' | VoiceTrivia';

        $fallback_coordinates = "{$project['location_lat']},{$project['location_lng']}";

        //$userModel    = new userModel();
        //$nearby_users = $userModel->getList();

        $current_user = null;
        $logged_in    = isset($_SESSION['user_id']) && isset($_SESSION['loggedin']) && $_SESSION['user_id'] && $_SESSION['loggedin'];

        if ($logged_in)
            $current_user = $userModel->getUser(['id' => $_SESSION['user_id']]);
			$user       = $_SESSION['loggedin'] ? $userModel->getUser($_SESSION['user_id']) : null; 

        if ($logged_in) {
            $userModel = new userModel();
            $favorites = $userModel->getFavorites($_SESSION['user_id'], userModel::FAVTYPE_PROJECT);

            $is_favorited_project = in_array($project['id'], array_keys($favorites));
        }
        
		if ($project['user_id'] == $_SESSION['user']['id'] || $_SESSION['user']['is_admin']) {
			if (isset($_GET['delete'])) {
				$challengesModel->delete((int)$_GET['delete']);
				//header("Location: /category/all");
				header("Location: /");
				exit;
			}
			if (isset($_GET['duplicate'])) {
				//echo "Duplicate works...";
				$project['title'] = $project['title'] . " - DUPLICATE"; 
				$new_dupe_id = $challengesModel->insert($project);
				//$new_dupe_id = $challengesModel->duplicate($project);
				//print_r($new_dupe_id);
				header("Location: /challenge/$new_dupe_id");
				exit;
			}			
		}
//        $can_redeem  = false;
//        $last_redeem = false;
//        $cnt_redeems = 0;
//        if ($logged_in) {
//            $redeems     = $challengesModel->getRedeems([
//                'user_id'    => $_SESSION['user_id'],
//                'project_id' => $project['id']]);
//            $cnt_redeems = count($redeems);
//            $can_redeem  = empty($project['redeem_max']) ? true : $project['redeem_max'] > $cnt_redeems;
//            $last_redeem = empty($redeems) ? false : $redeems[0];
//        }
//        $project_redeems = $challengesModel->getRedeems(['project_id' => $project['id']]);

    	require('views/challenge/details.tpl.php');
    }
    
    function sendNotif($phone,$ver_code){
    	
		//require_once realpath(dirname(__FILE__) . "/../3rdparty/twilio-php-master/Services") . "/Twilio.php";

//		$AccountSid = "ACc33ee9aa71e9a841111c0f6ef976af61";
//		$AuthToken = "774b5173cc5c1ba2b61ee20769888fa1";
//
//		$client = new Services_Twilio($AccountSid, $AuthToken);
//
//		$message = $client->account->messages->create(array(
//		"From" => "+13128789582",
//		"To" => $phone,
//		"Body" => "You received a new Bid/Proposal at VoiceTrivia.com. Visit https://voicetrivia.com to view it. To unsubscribe to these notifications, visit https://voicetrivia.com/unsubscribe/",
//		));	    	
			
    }

    function displayAddForm(){
        if (empty($_GET['sel_type']) || !is_numeric($_GET['sel_type']))
            exit;

        $type = $_GET['sel_type'];

        $is_ajax = true;
		
		$categoryModel = new categoryModel();
		$categories = $categoryModel->getList();				
        
//        $typesModel = new typesModel();
//        $types = $typesModel->getList();
//        
//        $talentModel = new talentModel();
//        $talents = $talentModel->getList();       

        if (listingModel::TYPE_CAMPAIGN == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_CAMPAIGN . "'>";
			require 'views/challenge/campaign/add.tpl.php';
            echo "</div>";

        elseif (listingModel::TYPE_JOB == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_JOB . "'>";
			require 'views/challenge/job/add.tpl.php';
            echo "</div>";

        elseif (listingModel::TYPE_DEAL == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_DEAL . "'>";
			require 'views/challenge/deal/add.tpl.php';
            echo "</div>";
			
        elseif (listingModel::TYPE_QUESTION == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_QUESTION . "'>";
			require 'views/challenge/question/add.tpl.php';
            echo "</div>";				
			
        elseif (listingModel::TYPE_BLOG == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_BLOG . "'>";
			require 'views/challenge/blog/add.tpl.php';
            echo "</div>";	

        elseif (listingModel::TYPE_EVENT == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_EVENT . "'>";
			require 'views/challenge/event/add.tpl.php';
            echo "</div>";	

        elseif (listingModel::TYPE_PRODUCT == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_PRODUCT . "'>";
			require 'views/challenge/product/add.tpl.php';
            echo "</div>";		

        elseif (listingModel::TYPE_OPINION == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_OPINION . "'>";
			require 'views/challenge/opinyun/add.tpl.php';
            echo "</div>";		

        elseif (listingModel::TYPE_SPACES == $type) :

            echo "<div class='add-project-wrapper' data-mode='" . listingModel::TYPE_SPACES . "'>";
			require 'views/challenge/spaces/add.tpl.php';
            echo "</div>";				

        endif;
        exit;
    }

    function add() {
        global $website_options;

		if (!$_SESSION['loggedin'] || $_SESSION['account_type'] != 'company' || ! $_SESSION['user']['is_admin']) {
            //header("Location: /?msg=You+are+not+allowed+to+create+deals");
            //exit;
        }

        // check the count of coupons which are active for the current business.
        // MAX ACTIVE COUPONS = 3
		$challengesModel = new challengesModel();
		$my_deals     = $challengesModel->getActiveDealsByUser($_SESSION['user_id']);
        if (count($my_deals) >= $website_options['max_active_deals']) {
            header("Location: /?msg=You+have+reached+your+listings+limit");
            exit;
        }

        $meta_title = "Create New Challenge";

		if ($_POST && $_SESSION['loggedin']) {

//			print_r($_POST);
//			exit;
			
            $challengesModel = new challengesModel();
            $userModel = new userModel();
            $notificationsModel = new notificationsModel();

			$pid = $challengesModel->insert($_POST);

            # Generate thumbnails
            //exec('php '.INDEX_FILE .' /service');
			exec('php-cli '.INDEX_FILE .' /service');

        	$followers = $userModel->getFollowers(['followed' => $_SESSION['user_id']]);
            foreach ($followers as $follower) {
            	$notificationsModel->insert([
            		'from_user_id' => $_SESSION['user_id'],
            		'user_id' => $follower['user_id_follower'],
            		'text' => "{$_SESSION['user']['name']} has posted something: <a href='/challenge/{$pid}'>{$_POST['title']}</a>"
            	]);
            }

            //$this->platformDump();
			header("Location: /challenge/$pid");
            exit;
        }

		require 'views/challenge/add.tpl.php';
    }
	function create(){
		global $website_options;

		if (!$_SESSION['loggedin']) {
			header("Location: /auth/login?msg=Please login first...");
			exit;
		}

		$meta_title = "Create New Challenge";

		require 'views/challenge/create.tpl.php';
	}
    function addnew() {
        global $website_options;

		if (!$_SESSION['loggedin']) {
			header("Location: /auth/login?msg=Please login first...");
			exit;
        }

        $meta_title = "Create New Challenge";
        
		$typesModel = new typesModel();
		$types = $typesModel->getList();
		
		$challengesModel = new challengesModel();
		$typesModel = new typesModel();
		$types = $typesModel->getList();

		$talentModel = new talentModel();
		$talents = $talentModel->getList();

		if ($_POST && $_SESSION['loggedin']) {
//			echo "<pre>";
//			print_r($_POST);
//			exit;
			$challengesModel = new challengesModel();
			$userModel = new userModel();
			$notificationsModel = new notificationsModel();

			if (empty($_POST['locspec']))
				$_POST['locspec'] = 0;
			else
				$_POST['locspec'] = 1;

			$_POST['project_type_id'] = 2;

			$pid = $challengesModel->insert($_POST);

			header("Location: /challenge/$pid");
			exit;
		}

    	require 'views/challenge/addnew.tpl.php';
    } 
    // for Marketplace > Selling
    function addlisting() {
        global $website_options;

		if (!$_SESSION['loggedin']) {
            //header("Location: /?msg=You+are+not+allowed+to+create+deals");
            //exit;
			header("Location: /auth/login?msg=Please login first...");
			exit;
        }

        // check the count of coupons which are active for the current business.
        // MAX ACTIVE COUPONS = 3
		$challengesModel = new challengesModel();
        $typesModel = new typesModel();
        $types = $typesModel->getList();

        $talentModel = new talentModel();
        $talents = $talentModel->getList();  
//        $my_deals     = $challengesModel->getActiveDealsByUser($_SESSION['user_id']);
//        if (count($my_deals) >= $website_options['max_active_deals']) {
//            header("Location: /?msg=You+have+reached+your+active+deals+limit");
//            exit;
//        }

        $meta_title = "Sell Something";

		if ($_POST && $_SESSION['loggedin']) {

//			print_r($_POST);
//			exit;

//$listing = [];
//$listing = [
//	[title] => 'Transport Ferrari from Chicago, IL to Santa Barbara, CA Home' 
//	[files] => ,
//	[timestamp_end] => 2023-10-04 10:00:27, 
//	[date_from] => 2023-10-05 
//	[date_to] => 2023-10-11 
//	[description] => 'Transport My Ferrari from Chicago, IL to Santa Barbara, CA Home',
//	[category_id] => 1,
//	[location] => 59 W North Blvd Chicago, IL 60610 
//	[location_lat] => 41.9108751 
//	[location_lng] => -87.6312098 
//	[location2] => 605 N Michigan Ave Chicago, IL 60605 
//	[location_lat2] => 41.892712 
//	[location_lng2] => -87.6237069 
//	[is_featured] => on 
//	[is_active] => on 
//	[budget] => 5000 
//	[terms] => Don't scratch it! 
//	[is_private] => 0 
//	[project_type_id] => 2
//];
			
            $challengesModel = new challengesModel();
            $userModel = new userModel();
            $notificationsModel = new notificationsModel();

//			print_r($_POST);
//			exit;

//			$_POST['project_type_id'] = 3;
//			$_POST['type_id'] = 11;
//			$_POST['main_img'] = "static/uploads/listings/default_deals_banner.png";

			if (empty($_POST['locspec']))
				$_POST['locspec'] = 0;
			else
				$_POST['locspec'] = 1;
			
			$_POST['project_type_id'] = 3;
			
			$pid = $challengesModel->insert($_POST);
            
			//print_r($data);
			//exit;
			//I'd like a talented Developer to create me a Buyer-Seller App for iOS and Android

            # Generate thumbnails
            //exec('php '.INDEX_FILE .' /service');
			//exec('php-cli '.INDEX_FILE .' /service');

//        	$followers = $userModel->getFollowers(['followed' => $_SESSION['user_id']]);
//            foreach ($followers as $follower) {
//            	$notificationsModel->insert([
//            		'from_user_id' => $_SESSION['user_id'],
//            		'user_id' => $follower['user_id_follower'],
//            		'text' => "{$_SESSION['user']['name']} has posted something: <a href='/listing/{$pid}'>{$_POST['title']}</a>"
//            	]);
//            }

            //$this->platformDump();
            header("Location: /challenge/$pid");
            exit;
        }

    	require 'views/challenge/addlisting.tpl.php';
    }   
    
    function addfast() {
        global $website_options;

		if (!$_SESSION['loggedin']) {
			header("Location: /auth/login?msg=Please login first...");
			exit;
        }

		$challengesModel = new challengesModel();
        $typesModel = new typesModel();
        $types = $typesModel->getList();

        $talentModel = new talentModel();
        $talents = $talentModel->getList();  

        $meta_title = "Create New Challenge";

		if ($_POST && $_SESSION['loggedin']) {

			$challengesModel = new challengesModel();
            $userModel = new userModel();
            $notificationsModel = new notificationsModel();

			$pid = $challengesModel->insert($_POST);

            header("Location: /challenge/$pid");
            exit;
        }

    	require 'views/challenge/addfast.tpl.php';
    }  
    
    function addsimple() {
        global $website_options;

		if (!$_SESSION['loggedin']) {
			header("Location: /auth/login?msg=Please login first...");
			exit;
        }

        $challengesModel = new challengesModel();
        $typesModel = new typesModel();
        $types = $typesModel->getList();

        $talentModel = new talentModel();
        $talents = $talentModel->getList();  

        $meta_title = "Add Simple Opp";

		if ($_POST && $_SESSION['loggedin']) {

			$challengesModel = new challengesModel();
            $userModel = new userModel();
            $notificationsModel = new notificationsModel();
			
			$_POST['simple'] = 1;
			$_POST['project_type_id'] = $_POST['type_id']; 
            $pid = $challengesModel->insert($_POST);

            header("Location: /challenge/$pid");
            exit;
        }

    	require 'views/challenge/addsimple.tpl.php';
    }  
    // ADD OPP - FOR BUYERS AND MOST FLIPS
    function addopp() {
        global $website_options;

		if (!$_SESSION['loggedin']) {
			header("Location: /auth/login?msg=Please login first...");
			exit;
        }

        $challengesModel = new challengesModel();
        $typesModel = new typesModel();
        $types = $typesModel->getList();

        $talentModel = new talentModel();
        $talents = $talentModel->getList();  

        $meta_title = "Add Opp";

		if ($_POST && $_SESSION['loggedin']) {

			$challengesModel = new challengesModel();
            $userModel = new userModel();
            $notificationsModel = new notificationsModel();
			
			//$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
			//or with the new PHP7 Null coalescing operator
			//$check_value = $_POST['my_checkbox_name'] ?? 0;
		
			if (empty($_POST['locspec']))
				$_POST['locspec'] = 0;
			else
				$_POST['locspec'] = 1;

			if (empty($_POST['collab']))
				$_POST['collab'] = 0;
			else
				$_POST['collab'] = 1;	
			
			if (empty($_POST['entries']))
				$_POST['entries'] = 0;
			else
				$_POST['entries'] = 1;			
			
			$_POST['fmeligible'] = 1;
			$_POST['project_type_id'] = $_POST['type_id']; 
			
//			echo "<pre>";
//			print_r($_POST);
//			exit;
			
            $pid = $challengesModel->insert($_POST);

            header("Location: /challenge/$pid");
            exit;
        }

		require 'views/challenge/addopp.tpl.php';
    }  
    
    function createmob() {
        global $website_options;

		if (!$_SESSION['loggedin']) {
			header("Location: /auth/login?msg=Please login first...");
			exit;
        }

        $challengesModel = new challengesModel();
        $typesModel = new typesModel();
        $types = $typesModel->getList();

        $talentModel = new talentModel();
        $talents = $talentModel->getList();  

        $meta_title = "Create a Challenge";

		if ($_POST && $_SESSION['loggedin']) {

			$challengesModel = new challengesModel();
            $userModel = new userModel();
            $notificationsModel = new notificationsModel();
			
			//$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
			//or with the new PHP7 Null coalescing operator
			//$check_value = $_POST['my_checkbox_name'] ?? 0;
		
			if (empty($_POST['locspec']))
				$_POST['locspec'] = 0;
			else
				$_POST['locspec'] = 1;

			if (empty($_POST['collab']))
				$_POST['collab'] = 0;
			else
				$_POST['collab'] = 1;	
			
			if (empty($_POST['fmeligible']))
				$_POST['fmeligible'] = 0;
			else
				$_POST['fmeligible'] = 1;	
			
			if (empty($_POST['entries']))
				$_POST['entries'] = 0;
			else
				$_POST['entries'] = 1;		
			
			if (empty($_POST['multi']))
				$_POST['multi'] = 0;
			else
				$_POST['multi'] = 1;		
			
			$_POST['project_type_id'] = 2; 
			
//			echo "<pre>";
//			print_r($_POST);
//			exit;
			
            $pid = $challengesModel->insert($_POST);

            header("Location: /challenge/$pid");
            exit;
        }

		require 'views/challenge/createmob.tpl.php';
    }  
    
    function adddeal() {
        global $website_options;

		if (!$_SESSION['loggedin']) {
			header("Location: /auth/login?msg=Please login first...");
			exit;
        }

        $challengesModel = new challengesModel();
        $typesModel = new typesModel();
        $types = $typesModel->getList();

        $talentModel = new talentModel();
        $talents = $talentModel->getList();  

        $meta_title = "Add New Listing";

		if ($_POST && $_SESSION['loggedin']) {

			$challengesModel = new challengesModel();
            $userModel = new userModel();
            $notificationsModel = new notificationsModel();

			$_POST['project_type_id'] = 3;
			$_POST['type_id'] = 11;
			$_POST['main_img'] = "static/uploads/projects/default_deals_banner.png";

            $pid = $challengesModel->insert($_POST);
			
			header("Location: /nearby");
            //header("Location: /listing/$pid");
            exit;
        }

    	require 'views/challenge/adddeal.tpl.php';
    }      
    
    function addquick() {
        global $website_options;

		if (!$_SESSION['loggedin']) {
			header("Location: /auth/login?msg=Please login first...");
			exit;
        }

        $challengesModel = new challengesModel();
        $typesModel = new typesModel();
        $types = $typesModel->getList();

        $talentModel = new talentModel();
        $talents = $talentModel->getList();  

        $meta_title = "Add New Listing";

		if ($_POST && $_SESSION['loggedin']) {

			$challengesModel = new challengesModel();
            $userModel = new userModel();
            $notificationsModel = new notificationsModel();

            $pid = $challengesModel->insert($_POST);

            header("Location: /category/all");
            exit;
        }

    	require 'views/challenge/addfast.tpl.php';
    }                  

    function edit() {
        global $website_options;

    	$id = $this->registry->args[1];

    	$categoryModel = new categoryModel();
		$marketplaceModel = new marketplaceModel();
		$challengesModel = new challengesModel();
        $userModel     = new userModel();
        //$campaignModel = new campaignModel();
        
		$typesModel = new typesModel();
		$types = $typesModel->getList();

		$talentModel = new talentModel();
		$talents = $talentModel->getList();

    	$project = $challengesModel->get($id);
//		echo "<pre>";
//		print_r($project);
    	
		if ($project['project_type_id']==2) {
			$categories = $categoryModel->getList();	
    	} else {
			$categories = $marketplaceModel->getList();
    	}

        if (empty($project)) {
            header("Location: /category/all");
            exit;
        }

    	if ($project['user_id'] != $_SESSION['user_id'] && !$_SESSION['user']['is_admin']) {
    		header("Location: /auth/login");
    		exit;
    	}

    	if (isset($_GET['deleteFile'])) {
    		$challengesModel->deleteFile((int)$_GET['deleteFile'], $id);
    		$project = $challengesModel->get($id);
    	}
    	
		if ($project['user_id'] == $_SESSION['user']['id'] || $_SESSION['user']['is_admin']) {
			if (isset($_GET['delete'])) {
				$challengesModel->delete((int)$_GET['delete']);
				header("Location: /");
				exit;
			}
		}

    	if ($_POST) {
//            if (!empty($_POST['campaign'])) {
//                $campaign = $_POST['campaign'];
//                $campaignModel->saveCampaign($campaign);
//            }

			if (empty($_POST['locspec']))
				$_POST['locspec'] = 0;
			else
				$_POST['locspec'] = 1;

			if (empty($_POST['collab']))
				$_POST['collab'] = 0;
			else
				$_POST['collab'] = 1;	
			
			if (empty($_POST['fmeligible']))
				$_POST['fmeligible'] = 0;
			else
				$_POST['fmeligible'] = 1;	
			
			if (empty($_POST['entries']))
				$_POST['entries'] = 0;
			else
				$_POST['entries'] = 1;			
			
			if ($_POST['type_id']==5) {
				$_POST['project_type_id'] = 3; 	
			} else {
				$_POST['project_type_id'] = 2; 
			}

            if (empty($_POST['is_active']))
                $_POST['is_active'] = 0;
            else
                $_POST['is_active'] = 1;
			
            if (empty($_POST['is_featured']))
                $_POST['is_featured'] = 0;
            else
                $_POST['is_featured'] = 1;	
            
			if (empty($_POST['multi']))
				$_POST['multi'] = 0;
			else
				$_POST['multi'] = 1;	
            
//			echo "<pre>";
//			print_r($_POST);
//			exit;		

    		$challengesModel->update($id, $_POST);
    		//header("Location: /challenge/$id");
			header("Location: /challenge/$id/edit?saved");
    		exit;
    	}

        //$businesses = $userModel->getList(['account_type' => "Company"]);

		// https://voicetrivia.com/challenge/201/edit
    	require('views/challenge/edit.tpl.php');
    	exit;
    }
 
    public function upload() {
        $response = array('status' => 'error');
        if (!empty($_FILES['ufile'])) {
            do {
                $file = $_FILES['ufile'];
                if ($file['error']) {
                    $response['code'] = 1;
                    break;
                }

                if ($file['size'] > 1024*1024*10) {
                    $response['code'] = 2;
                    break;
                }

                $type = null;
                if (!empty($_POST['type']) && $_POST['type'] == 'image') {
                    $type = 'image';
                }

                $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ['php', 'htm', 'html', 'php4', 'php5', 'htaccess'])) {
                    $response['code'] = 3;
                    break;
                }

                if ($type == 'image' && ($ext != 'jpg' && $ext != 'png' && $ext != 'jpeg')) {
                    $response['code'] = 4;
                    break;
                }

                $filename = sha1($file['tmp_name']);

                $destination = "static/uploads/projects/$filename.$ext";
                if (!file_exists($destination)) {
                    //if ($type == 'image') {
                    //    autoRotateImage($file['tmp_name']);
                    //}

                    move_uploaded_file($file['tmp_name'], $destination);
                }

                $uploadsModel = new uploadsModel();
                $id = $uploadsModel->insert($destination, $type, $file['name']);

                $response['status'] = 'ok';
                $response['id'] = $id;
            } while (0);
        }

        echo json_encode($response);
        exit;
    }

    function hireCandidate(){
        global $website_options;

        $project_id  = $this->registry->args[2];
        $proposal_id = $this->registry->args[3];

        $challengesModel = new challengesModel();
        $userModel    = new userModel();
        $project      = $challengesModel->get($project_id);
        $the_proposal = $challengesModel->getProposal($proposal_id);
        $proposals    = $challengesModel->getProposals($project_id);
        $candidates   = [];
        foreach ($proposals as $proposal)
            $candidates[$proposal['user_id']] = $userModel->getUser($proposal['user_id']);

        $candidate = $candidates[$the_proposal['user_id']];

        if (!empty($website_options['proposal_amount_fee']))
            // APPLY FEE
            $the_proposal['amount'] = number_format(($the_proposal['amount'] + ($the_proposal['amount'] * ($website_options['proposal_amount_fee'] / 100))), 2);

        $paypal_website_email = empty($website_options['paypal_email']) ? "voicemenuapp@gmail.com" : $website_options['paypal_email'];

        require 'views/challenge/job/hire-candidate.tpl.php';
    }

    function ajaxToggleProposalStatus(){
		// add this in one day || empty($_POST['uid'])
		if (empty($_POST) || empty($_POST['aid']) || empty($_POST['status'])) {
            echo "-1";
            exit;
        }
        
//		echo json_encode($_POST); // gets us a view of the POST variables
//		exit;

        $aid    = $_POST['aid']; // Offer/Proposal ID
		$pid 	= $_POST['pid']; // Listing ID
		$uid 	= $_POST['uid']; // User ID
        $status = $_POST['status'];
        
		// "created", "hired", "accepted", "completed", "reviewed", "withdrawn"
		if ($status == 1) {
			$pstatus = "hired";
		} elseif($status == 2){
			$pstatus = "accepted";
		} elseif($status == 3){
			$pstatus = "completed"; // Set to Complete/Fulfilled
		} elseif($status == 4){
			$pstatus = "reviewed"; // "reviewed" that the order was fulfilled and released escrow
		} elseif($status == 5){
			$pstatus = "withdrawn"; // Set it to this AFTER both reviews are submitted
		} else {
			//$pstatus = "created";
		}
		// amount, escrow, user_id
        $challengesModel = new challengesModel();
		if ($status == 4) {
			$challengesModel->transferEscrow($aid,$uid);
        }
		$res = $challengesModel->setProjectStatus($pid, $pstatus);
        echo $challengesModel->setProposalStatus($aid, $status);
        exit;
    }
    
	function updateBalance(){
		if (empty($_POST) || empty($_POST['pid']) || empty($_POST['uid'])) {
			echo "-1";
			exit;
		}

//		echo json_encode($_POST); // gets us a view of the POST variables
//		exit;
		$pid 	= $_POST['pid']; // Listing ID
		$uid 	= $_POST['uid']; // User ID	
		
		$squareusersModel = new squareusersModel();
		if ($_SESSION['loggedin'] && $_SESSION['user']['id']) {
			$user_bal = $squareusersModel->getBalance($uid);
			//print_r($user);
			$_SESSION['user']['virtual_balance'] = $user_bal;
			echo $user_bal;
			//echo json_encode($user_bal);
			exit;
		}
	}

    function acceptJob(){
		// https://voicetrivia.com/challenge/acceptJob?uid=296&pid=201&st=2
		
        if (! empty($_GET)) :
            $project_id = $_GET['pid'];
            $user_id    = $_GET['uid'];
            $status     = $_GET['st'];
        elseif (! empty($_POST)) :
            $project_id  = $_POST['pid'];
            $proposal_id = $_POST['rid'];
            $user_id     = $_POST['uid'];
            $status      = $_POST['st'];
        endif;

        $challengesModel = new challengesModel();
        $userModel    = new userModel();

        $project  = $challengesModel->get($project_id);
//		print_r($project);
//		exit;
		// MUST BE STATUS 1 (IE. HIRED) IN THE PROPOSALS TABLE
        $proposal = $challengesModel->getHiredProposal($project_id);
//		echo "<pre>";
//		print_r($proposal);
//		exit;

// 0 - "created",
// 1 - "hired",
// 2 - "accepted",
// 3 - "completed",
// 4 - "reviewed",
// 5 - "withdrawn

        $user     = $challengesModel->getHiredCandidate($project_id);
//		echo "<pre>";
//		print_r($user);
//		exit;
		
        if ($user_id != $user['id'])
            /* hired candidate is not the person who initiated
               the request, this should never happen. */
            exit;

        if (! empty($_POST)) {
            // handle POST request, should set the project as Accepted.
            // This is done by the CANDIDATE
            $res = $challengesModel->setProjectStatus($project_id, 'accepted');
            header("Location: /challenge/{$project_id}");
            exit;
        }

        //require 'views/challenge/job/accept-job.tpl.php'; // Lightbox
		require 'views/challenge/job/acceptJob.tpl.php';
    }

    function completeJob()
    {
        if (! empty($_GET)) :
            $project_id = $_GET['pid'];
            $user_id    = $_GET['uid'];
            $status     = $_GET['st'];
        elseif (! empty($_POST)) :
            $project_id  = $_POST['pid'];
            $proposal_id = $_POST['rid'];
            $user_id     = $_POST['uid'];
            $status      = $_POST['st'];
        endif;

        $challengesModel = new challengesModel();
        $userModel    = new userModel();

        $project  = $challengesModel->get($project_id);
        $proposal = $challengesModel->getHiredProposal($project_id);
        $user     = $challengesModel->getHiredCandidate($project_id);

        if ($user_id != $user['id'])
            /* hired candidate is not the person who initiated
               the request, this should never happen. */
            exit;

        if (! empty($_POST)) {
            // handle POST request, should set the project as Completed.
            // This is done by the CANDIDATE
            $res = $challengesModel->setProjectStatus($project_id, 'completed');
            header("Location: /challenge/{$project_id}");
            exit;
        }

        require 'views/challenge/job/set-completed-job.tpl.php';
    }

    function reviewJob()
    {
        if (! empty($_GET)) :
            $project_id = $_GET['pid'];
            $user_id    = $_GET['uid'];
            $status     = $_GET['st'];
        elseif (! empty($_POST)) :
            $project_id  = $_POST['pid'];
            $proposal_id = $_POST['rid'];
            $user_id     = $_POST['uid'];
            $status      = $_POST['st'];
        endif;

        $challengesModel = new challengesModel();
        $userModel    = new userModel();

        $project  = $challengesModel->get($project_id);
        $proposal = $challengesModel->getHiredProposal($project_id);

        if ($user_id != $project['user_id'])
            /* project owner is not the person who initiated
               the request, this should never happen. */
            exit;

        if (! empty($_POST)) {
            // handle POST request, should set the project as Reviewed.
            // This is done by the PROJECT OWNER

            // first set the rating for this candidate.
            if ($_POST['submit_rating'])
                $challengesModel->submitCandidateRating($_POST['submit_rating'], $_POST['rid']);

            $res = $challengesModel->setProjectStatus($project_id, 'reviewed');
            header("Location: /challenge/{$project_id}");
            exit;
        }

        require 'views/challenge/job/review-job.tpl.php';
    }

    function requestWithdrawal()
    {
        if (! empty($_GET)) :
            $project_id = $_GET['pid'];
            $user_id    = $_GET['uid'];
            $status     = $_GET['st'];
        elseif (! empty($_POST)) :
            $project_id  = $_POST['pid'];
            $proposal_id = $_POST['rid'];
            $user_id     = $_POST['uid'];
            $status      = $_POST['st'];
        endif;

        $challengesModel = new challengesModel();
        $userModel    = new userModel();

        $project  = $challengesModel->get($project_id);
        $proposal = $challengesModel->getHiredProposal($project_id);
        $user     = $challengesModel->getHiredCandidate($project_id);

        if ($user_id != $user['id'])
            /* hired candidate is not the person who initiated
               the request, this should never happen. */
            exit;

        if (! empty($_POST)) {
            // handle POST request, should set the project as Accepted.
            $res = $challengesModel->setProjectStatus($project_id, 'withdrawn');
            header("Location: /challenge/{$project_id}");
            exit;
        }

        require 'views/challenge/job/request-withdrawal.tpl.php';
    }

    function selectCandidate()
    {
        global $website_options;

        if (empty($_SESSION['user_id']))
            exit;

        $user_id    = $_GET['uid'];

        $challengesModel = new challengesModel();
        $userModel    = new userModel();

        // only display projects for which the candidate
        // has sent proposals and which are not yet completed.
        $projects = $challengesModel->getList([
            'user_id'       => $_SESSION['user_id'],
            'status'        => 'created']);
        $user     = $userModel->getUser($user_id);

        $paypal_website_email = empty($website_options['paypal_email']) ? "voicemenuapp@gmail.com" : $website_options['paypal_email'];

        require 'views/challenge/job/select-candidate.tpl.php';
    }

    function summary()
    {
        if (empty($_GET['uid']))
            exit;

        $user_id    = $_GET['uid'];

        $challengesModel = new challengesModel();
        $userModel    = new userModel();

        $user      = $userModel->getUser($user_id);
        $proposals = $userModel->getProposals($user_id, true);

        // projects I worked on
        $work_projects  = [];
        foreach ($proposals as $prop) {
            if (!in_array($prop['project_id'], array_keys($work_projects))) {
                $work_projects[$prop['project_id']] = $challengesModel->get($prop['project_id']);
                $work_projects[$prop['project_id']]['proposal'] = $prop;
            }
        }

        // project I own
        $my_projects = $challengesModel->getList(['user_id' => $user_id]);

        require 'views/challenge/job/user-summary.tpl.php';
    }

    function invite()
    {
        if (empty($_POST))
            $id = $this->registry->args[2];
        else
            $id = $_POST['pid'];

        $challengesModel = new challengesModel();
        $userModel  = new userModel();

        $users      = $userModel->getList();
        $project    = $challengesModel->get($id);

        if (!empty($_POST)) {
            // form sent - send invitations.
            $invited_users = $_POST['invited_users'];
            foreach ($invited_users as $uid)
                $challengesModel->inviteUser($project['id'], $uid);

            header("Location: /challenge/" . $project['id']);
            exit;
        }

        require('views/challenge/invite.tpl.php');
    }

    function acceptInvite()
    {
        $pid = $this->registry->args[2];
        $uid = $this->registry->args[3];

        if (empty($pid ) || empty($uid)) {
            header("Location: /category/all");
            exit;
        }

        // make sure objects by ID are valid.
        $gm    = new challengesModel();
        $um    = new userModel();
        $project = $gm->get($pid);
        $user    = $um->getUser($uid);

        $gm->toggleJoin($project['id'], $user['id'], true);
        header("Location: /challenge/" . $project['id']);
        exit;
    }
    // COMMENTS
	function addComment()
	{
		if (!$_SESSION['user_id']) {
			die("Please log in");
		}
		$commentModel = new commentModel();

		$comment = $_POST;

		$comment['user_id'] = $_SESSION['user_id'];

		//print_r($comment);
		$commentModel->insert($comment);

		die('ok');
	}
	
	function editContr(){
		$challengesModel = new challengesModel();
		$contribution = $_POST;
		
		$challengesModel->updateContr($contribution);
		
//		echo json_encode($_POST);
//		exit;
		//echo $_POST['submit'];
		//$origPledge = $listingModel->getpledge($_POST['id']);
		
//		echo json_encode($origPledge);
//		exit;	
		
//		if ($origPledge['escrow']==0 && isset($_POST['escrow'])) {
////			$status = "New Escrow!";
////			echo json_encode($status);
////			exit;
//			// THIS MEANS IT'S A NEW ESCROW 
//			$listingModel->updateContrwithEscrow($contribution);
//		} else if ($origPledge['escrow']==1 && isset($_POST['escrow'])) {
//			// Could be an increase of escrow or no escrow change at all in pledge amount and just a comment change
//			$listingModel->updateContrwithEscrow($contribution);
//		} else {
//			// Basically Escrowed or Not and unchecking of the Escrow
////			$status = "NO Escrow!";
////			echo json_encode($status);
////			exit;
//			$listingModel->updateContr($contribution);
//		}
	}
	
	function commentNEW(){
		$id         = $this->registry->args[2];
		$challengesModel = new challengesModel();
		$project      = $challengesModel->get($id);
		
		$ver_code = $challengesModel->getUserVerCode($project['user_id']);	
//		print_r($ver_code);
//		exit;

		$comment_id = $challengesModel->postComment(array(
			"user_id"  => $_SESSION['user_id'],
			"project_id" => $project['id'],
			"content"  => $_POST['message'])
		);
		
		$receiver_email = $project['email'];
		$receiver_phone = $project['phone'];
		
//		print_r($receiver_email);
//		exit;
		
		// LET'S SEND THE USER AN EMAIL NOTIFICATION
//		$messageSubject = "New Comment Alert! - VoiceTrivia.com!";
//		$messageBody = "You received a new comment on your Listing at VoiceTrivia.com.<br /><br />
//		Visit https://voicetrivia.com to view it...";
//		
//		$unsubscribe = "https://voicetrivia.com/unsubscribe/" . $ver_code;
		
		// HTML FORMATTED MESSAGE EXAMPLE GSIVSpw (ver_code - silly)
//		$msg= "<div style='text-align:left; max-width:600px; margin:0 auto; background:#eee; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; overflow:hidden; font-family:Helvetica,Verdana,sans-serif;'>
//	<div style='padding:15px; background:#fff; margin:10px'>
//		<center><img src='https://voicetrivia.com/static/system/email_hdr.jpg' style='width:100%;' /></center>
//		<br /><br />
//		Hi,
//		<br /><br />
//		You received a new comment on your Listing at VoiceTrivia.com.
//		<br /><br />
//		Visit https://voicetrivia.com to view it...
//		<br /><br />
//		Thank you,
//		<br /><br />
//		- VoiceTrivia
//		<br /><br />
//		<center><span style='color:#aaa'>- - - - - - -</span>
//			<br /><br />
//			If you would like to stop receiving all emails from VoiceTrivia.com, simply click
//			$unsubscribe - or you can also manage all your Unsubscribe Settings in the Notifications
//			section on the Edit Account page at voicetrivia.com.</center>
//	</div>
//</div>"; 	
//
//		$headers = "MIME-Version: 1.0" . "\r\n";
//		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
//
//		$headers .= 'From: VoiceTrivia.com <noreply@voicetrivia.com>' . "\r\n";
//		$headers .= 'Reply-To: VoiceTrivia.com <noreply@voicetrivia.com>';	
//	
//		@mail($receiver_email, $messageSubject, $msg, $headers, '-fnoreply@voicetrivia.com');	
	
		// LET'S SEND THE USER A TEXT NOTIFICATION
		require_once realpath(dirname(__FILE__) . "/../3rdparty/twilio-php-master/Services") . "/Twilio.php";

//		$AccountSid = "ACc33ee9aa71e9a841111c0f6ef976af61";
//		$AuthToken = "774b5173cc5c1ba2b61ee20769888fa1";
//
//		$client = new Services_Twilio($AccountSid, $AuthToken);
//
//		$message = $client->account->messages->create(array(
//			"From" => "+13128789582",
//			"To" => $receiver_phone,
//			"Body" => "You received a new comment at VoiceTrivia.com. Visit https://voicetrivia.com to view it. To unsubscribe to these notifications, visit https://voicetrivia.com/unsubscribe/".$ver_code,
//		));			

		echo $comment_id;
		exit;
	}
	
	function comment(){
		$id         = $this->registry->args[2];
		$challengesModel = new challengesModel();
		$project      = $challengesModel->get($id);
//		print_r($ver_code);
//		exit;

		$comment_id = $challengesModel->postComment(array(
			"user_id"  => $_SESSION['user']['id'],
			"project_id" => $project['id'],
			"content"  => $_POST['message'])
		);		

		echo $comment_id;
		exit;
	}

	function commentlist()
	{
		$id           = $this->registry->args[2];
		$challengesModel = new challengesModel();
		$project      = $challengesModel->get($id);

		require 'views/challenge/comments.tpl.php';
	}  
	
	// CHIP-INS & JOIN CHALLENGE - test it here: https://voicetrivia.com/challenge/chipin/201 
	// Line 1257 is editContr
	function chipin(){
		$id           = $this->registry->args[2];
		$challengesModel = new challengesModel();
		//$userModel = new userModel();
		$project      = $challengesModel->get($id);
		
		$ver_code = $challengesModel->getUserVerCode($project['user_id']);
//		print_r($ver_code);
//		exit;
		
		$nowtime = new DateTime; 
		$now_time = date('Y-m-d H:i:s');
		
		if (!empty($_POST['escrowAmt'])) {
			$escrowAmount = $_POST['escrowAmt'];
		}
		
		if ($_POST['chipinmult']==1) {
			$multval = 1;
		}

		$chipin_id = $challengesModel->postChipin(array(
			"user_id"  		=> $_SESSION['user_id'],
			"project_id" 	=> $project['id'],
			"comment"  		=> $_POST['comment'],
			"rating"   		=> $_POST['rating'],
			"prevamt"		=> $_POST['rating'],
			"created_at" 	=> $now_time,
			"escrow"		=> $_POST['escrow'],
			"escrowAmt"		=> $escrowAmount,
			"escrowPrev"	=> $escrowAmount,
			"mult"			=> $multval
			)
		);

		$receiver_email = $project['email'];
		$receiver_phone = $project['phone'];
		
		// LET'S SEND THE USER AN EMAIL NOTIFICATION
		$messageSubject = "New VoiceTrivia Player Alert! - VoiceTrivia.com";
		$messageBody = "A new player just joined your Challenge!<br /><br />
		Visit VoiceTrivia at https://voicetrivia.com to see who it is...";
		
		$unsubscribe = "https://voicetrivia.com/unsubscribe/" . $ver_code;
		
		// HTML FORMATTED MESSAGE EXAMPLE GSIVSpw (ver_code - silly)
		$msg= "<div style='max-width:580px; margin:0 auto; background:#fff; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; overflow:hidden; font-family:Helvetica,Verdana,sans-serif; padding:0; border:10px solid #eee;'>
		<div style='width:100%; max-height:150px; overflow:hidden; padding:0; margin:0 auto;'>
			<center><img src='https://voicetrivia.com/static/system/email_hdr_img.jpg'
			style='width:100%; display:block; background-size:cover; object-fit:cover' /></center>
		</div>
		<div class='clear'></div>
		<div style='border-bottom:2px solid #eee; margin:0 auto; max-width:60%;'></div>
		<div style='padding:15px; background:#fff; text-align:left;'>
			Hi,
			<br /><br />
			A new player just joined your Challenge at VoiceTrivia.com
			<br /><br />
			Visit https://voicetrivia.com to see who it is...
			<br /><br />
			Thank you,
			<br /><br />
			- VoiceTrivia
			<br /><br />
			<center><span style='color:#aaa'>- - - - - - -</span>
			<br /><br />
			If you would like to stop receiving all emails from VoiceTrivia.com, simply click
			$unsubscribe - or you can also manage all your Unsubscribe Settings in the Notifications
			section on the Edit Account page at voicetrivia.com.</center>
		</div>
		<div class='clear'></div>
		</div>"; 	

		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

		$headers .= 'From: VoiceTrivia.com <noreply@voicetrivia.com>' . "\r\n";
		$headers .= 'Reply-To: VoiceTrivia.com <noreply@voicetrivia.com>';	
	
		//@mail($receiver_email, $messageSubject, $msg, $headers, '-fnoreply@voicetrivia.com');	
	
		// LET'S SEND THE USER A TEXT NOTIFICATION
//		require_once realpath(dirname(__FILE__) . "/../3rdparty/twilio-php-master/Services") . "/Twilio.php";
//
//		$AccountSid = "ACc33ee9aa71e9a841111c0f6ef976af61";
//		$AuthToken = "774b5173cc5c1ba2b61ee20769888fa1";
//
//		$client = new Services_Twilio($AccountSid, $AuthToken);
//
//		$message = $client->account->messages->create(array(
//			"From" => "+13128789582",
//			"To" => $receiver_phone,
//			"Body" => "You received new interest from a potential Co-Funder at VoiceTrivia.com. Visit https://voicetrivia.com to see who it is. To unsubscribe to these notifications, visit https://voicetrivia.com/unsubscribe/".$ver_code,
//		));				

		echo $chipin_id;
		exit;
	}

	function chipinlist(){
		$id         = $this->registry->args[2];
		$challengesModel = new challengesModel();
		$project      = $challengesModel->get($id);

		require 'views/challenge/chipins.tpl.php';
	}	  
	
	function chipinwithdraw(){
		$id         = $this->registry->args[2];
		$challengesModel = new challengesModel();
		
		$chipin_id = $_POST['id']; 
		$amount = $_POST['amount']; 
		$userID = $_POST['userid'];
//		echo $id; 
//		exit;

		// RESTORE THE PLEDGE AMOUNTS TO THE USER'S BALANCE
		//$userModel = new userModel();
		$pledge     = $challengesModel->getpledge($chipin_id);
		
		if ($pledge && $pledge['escrow'] == 1) { }
			
//		$amount = $pledge['escrowAmt']; // raw dollar amount
//		$userID = $pledge['user_id'];
		$challengesModel->restoreEscrow($userID, $amount);
		//$challengesModel->adjustAlreadyPaid($pledge['project_id'], $amount);
		$challengesModel->adjustAlreadyPaid($pledge['project_id'], $amount);
		
		//$challengesModel->adjustTotals($pledge['rating'],$pledge['project_id']);
		$challengesModel->adjustTotals($amount,$pledge['project_id']);
		
		// BY DELETING THE CO-FUND RECORD, THE COFUNDED AMT IS AUTOMATICALLY UPDATED
		$challengesModel->deletecofunder($chipin_id);
		echo 1;
		exit;
	}	

    function togglejoin()
    {
        if (empty($_POST['uid']) || empty($_POST['pid']))
            exit;

        $user_id    = $_POST['uid'];
        $project_id = $_POST['pid'];

        $challengesModel = new challengesModel();
        $is_joined    = $challengesModel->toggleJoin($project_id, $user_id);

        echo $is_joined ? "1" : "0";
        exit;
    }

    function addDispute()
    {
        if (! empty($_GET)) :
            $project_id = $_GET['pid'];
            $user_id    = $_GET['uid'];
        elseif (! empty($_POST)) :
            $project_id  = $_POST['pid'];
            $user_id     = $_POST['uid'];
            $message     = $_POST['msg'];
        endif;

        $challengesModel = new challengesModel();
        $userModel    = new userModel();

        $project  = $challengesModel->get($project_id);
        $user     = $userModel->getUser($user_id);

        if (! empty($_POST)) {
            // handle POST request, should save the dispute.
            $res = $challengesModel->saveDispute($project_id, $user_id, $message);

            header("Location: /challenge/{$project_id}");
            exit;
        }

        require 'views/challenge/job/add-dispute.tpl.php';
    }

    function readProposal()
    {
        if (empty($_GET['uid']) || empty($_GET['rid']))
            exit;

        $userModel    = new userModel();
        $challengesModel = new challengesModel();

        $user     = $userModel->getUser($_GET['uid']);
        $proposal = $challengesModel->getProposal($_GET['rid']);

        require 'views/challenge/job/view-proposal.tpl.php';
    }

    function sendProposal(){
        if (empty($_GET['pid'])) {
            header("Location: /challenge");
            exit;
        }

        $challengesModel = new challengesModel();

        $pid     = $_GET['pid'];
        $project = $challengesModel->get($pid);

        require 'views/challenge/job/send-proposal.tpl.php';
    }

    function sendOffer(){
        if (empty($_GET['pid'])) {
            header("Location: /marketplace/all");
            exit;
        }

        $challengesModel = new challengesModel();

        $pid     = $_GET['pid'];
        $project = $challengesModel->get($pid);

        require 'views/challenge/job/send-offer.tpl.php';
    }
    
    function withdrawOffer(){
		$prjid      = $this->registry->args[2];
		$id         = $this->registry->args[3];
		$challengesModel = new challengesModel();   
		
//		echo $id;
//		exit;
		
		$challengesModel->deleteOffer($id);
		header("Location: /challenge/$prjid?msg=Withdrawn");
//		echo 1;
//		exit;
	}
	
	function escrowOffer(){
//		$prjid      = $this->registry->args[2];
//		$id         = $this->registry->args[3];
		$challengesModel = new challengesModel(); 
		
		$id = $_POST['aid'];
		$prjid = $_POST['pid'];
		
		// GET THE OFFER RECORD
		$offer = $challengesModel->escrowOffer($id);
		
//		echo "<pre>";
//		print_r($offer);
		
//		echo $_SESSION['user']['virtual_balance'] . "<br />"; // 31,500.00 or 3150000
		
//		echo $offer['amount'] * 100 . "<br />";
		
		$userBal  = $_SESSION['user']['virtual_balance'];
		
		if ($offer['amount']>0) {
			$offerAmt = $offer['amount'] * 100;	
		}
		
		if ($userBal > $offerAmt) {
			// REDUCE THE USER'S BALANCE
			$reduceStatus = $challengesModel->reduceBalance($_SESSION['user']['id'],$offerAmt);
			if ($reduceStatus ==1) {
				$_SESSION['user']['virtual_balance'] = $_SESSION['user']['virtual_balance'] - $offerAmt;
			}
			
			$res = $challengesModel->setProjectStatus($prjid, 'accepted');
			$res2 = $challengesModel->setProposalStatus($id, 2);
			
			// IF THE USER HAS ENOUGH FUNDS, ESCROW IT
			$escrowStatus = $challengesModel->setEscrow($id);
			if ($escrowStatus == 1) {
				echo 1;	
			} else {
				echo 0;
			}
			//echo "Ok, we can escrow this...";
			//header("Location: /challenge/$prjid?msg=Escrowed");
		} else {
			echo 0;
//			echo "Nope, we cannot escrow this...";
		}
		
//		[id] => 72
//		[project_id] => 196
//		[user_id] => 4
//		[rating] => 0
//		[text] => I'd like to buy this.
//		[amount] => 400.00
//		[days] =>
//		[status] => 0
//		[id_upload] => 1231
//		[timestamp] => 2024-03-24 03:52:39
		
//		if ($confirmEscrow) {
//			header("Location: /challenge/$prjid?msg=Escrowed");	
//		} else {
//			header("Location: /challenge/$prjid?msg=EscrowError");
//		}
	}
	
	function acceptOffer(){
		$project_id  = $this->registry->args[2];
		$offer_id = $this->registry->args[3];

		$status = "hired";

		if (empty($offer_id)) {
			//header("Location: /profile/allproposals");
			header("Location: /challenge/".$project_id);
			exit;
		}

		$challengesModel = new challengesModel();
		
		echo $project_id . "<br />";
		echo $offer_id . "<br />";
		exit;

		$challengesModel->setProjectStatus($project_id, $status);
		// save the candidate/provider's id to the faciliator column
		$hiredStatus = $challengesModel->acceptTheOffer($offer_id);

		if ($hiredStatus==1) {
			header("Location: /challenge/$prjid?msg=Accepted"); // need to make a msg status for this
			//forward to milestones
			//header("Location: /profile/allproposals?msg=withdrawn");
		}
	}
	
	function editMultiOffer(){
		if (empty($_GET['uid']) || empty($_GET['oid']))
			exit;

		$userModel    = new userModel();
		$projectModel = new projectModel();

		$user     = $userModel->getUser($_GET['uid']);
		$multioffer = $projectModel->getpledge($_GET['oid']);

		require 'views/challenge/job/view-offer.tpl.php';
	}
	
	function updateMOffer(){
//		print_r($_POST);
//		exit;
		$challengesModel = new challengesModel();
		$challengesModel->updateMultiOffer($_POST);
		
		//require 'views/challenge/job/view-offer.tpl.php';
		
		//$challengesModel->update($id, $_POST);
		header("Location: /challenge/".$_POST['project_id']);
//		header("Location: /challenge/".$_POST['id']."?saved");
//		exit;
	}
	
	function updateOffer(){
//		print_r($_POST);
//		exit;
		$challengesModel = new challengesModel();
		$challengesModel->updateOffer($_POST);
		
		//require 'views/challenge/job/view-offer.tpl.php';
		
		//$challengesModel->update($id, $_POST);
		header("Location: /challenge/".$_POST['project_id']);
//		header("Location: /challenge/".$_POST['id']."?saved");
//		exit;
	}

    public function ajaxToggleFavorite()
    {
        if (empty($_POST) || empty($_POST['uid']) || empty($_POST['pid'])) {
            echo "-1";
            exit;
        }

        $oid = $_POST['pid'];
        $uid = $_POST['uid'];

        $userModel = new userModel();
        $res = $userModel->toggleFavorite($uid, $oid, userModel::FAVTYPE_PROJECT);

        // true = added ; false = removed
        echo ($res ? "1" : "0");
        exit;
    }

    public function redeemDeal()
    {
        if (empty($_GET['uid']) || empty($_GET['pid']) || !is_numeric($_GET['uid']) || !is_numeric($_GET['pid']))
            exit;

        $challengesModel = new challengesModel();
        $userModel    = new userModel();

        $project = $challengesModel->get($_GET['pid']);
        $user    = $userModel->getUser($_GET['uid']);

        $result  = $challengesModel->saveRedeem($project['id'], $user['id']);
        $redeems = $challengesModel->getRedeems(['project_id' => $project['id']]);

        if ($result) {
            // redeem done.
            $can_redeem  = empty($project['redeem_max']) || $project['redeem_max'] > count($redeems);
            $last_redeem = $redeems[0];

            $last_redeem['date_created'] = date("m/d/Y H:i", strtotime($last_redeem['date_created']));

            echo '{"can_redeem": "' . ($can_redeem ? "1" : "0") . '", "cnt_redeems": "' . count($redeems) . '", "redeem": ' . json_encode($last_redeem) . '}';
        }
        exit;
    }

    public function testCampaign()
    {
        $campaignModel = new campaignModel();
        $matches_for_campaigns = $campaignModel->getMatchesByCampaign();

        echo "<h1>Currently Active Campaigns: </h1>";
        echo "<table><thead><th>Campaign ID</th><th>Count Matches</th><th>Matches</th><th>SQL</th></thead><tbody>";
        foreach ($matches_for_campaigns as $campaign_id => $results) {
            echo "<tr style='border-bottom: 1px solid #000;'>";
            echo "<td align='center'>{$campaign_id}</td>";
            echo "<td align='center'>{$results['count']}</td>";
            echo "<td><ul>";
            foreach ($results['matches'] as $ix => $user)
                echo "<li>{$user->name} ({$user->email})</li>";
            echo "</ul></td>";
            echo "<td>{$results['sql']}</td>";
            echo "</tr>";
        }
        echo "</tbody></table>";
        exit;
    }

    function getNearbyProjects()
    {
        global $website_options;

        if (empty($_GET['latitude']) || empty($_GET['longitude'])) {
            // Staunton, VA
            $_GET['latitude']  = 38.149576;
            $_GET['longitude'] = -79.0716958;
        }

        $userModel    = new userModel();
        $challengesModel = new challengesModel();

        $nearby_cond = [
            'nearby_search' => 1,
            'latitude'      => $_GET['latitude'],
            'longitude'     => $_GET['longitude'],
            'is_active'     => 1,
            'project_type_id' => listingModel::TYPE_DEAL,
        ];

        $search_category = $_GET['search_category'];
        $search_distance = $_GET['search_distance'];
        if (!empty($search_category))
            $nearby_cond['category_id'] = $search_category;

        if (!empty($search_distance))
            $nearby_cond['distance'] = $search_distance;

        $search_term     = $_GET['term'];
        if (!empty($search_term))
            $nearby_cond['search'] = $search_term;

        $nearby_projects = $challengesModel->getList($nearby_cond);
        $is_mobile       = isset($_GET['is_mobile']) && $_GET['is_mobile'];

        require 'views/challenge/nearby-projects-list.tpl.php';
    }
    
    ///////////////////////////////////////////
    // NOTIFICATIONS START HERE 
	///////////////////////////////////////////
	
	function sendProposalNotification($receiver_email, $ver_code){
		// LET'S SEND THE USER AN EMAIL NOTIFICATION
		$messageSubject = "New Offer Alert! - VoiceTrivia.com!";
		
		$unsubscribe = "https://voicetrivia.com/unsubscribe/" . $ver_code;
		
		// HTML FORMATTED MESSAGE EXAMPLE GSIVSpw (ver_code - silly)
		$msg= "<div style='max-width:580px; margin:0 auto; background:#fff; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; overflow:hidden; font-family:Helvetica,Verdana,sans-serif; padding:0; border:10px solid #eee;'>
		<div style='width:100%; max-height:150px; overflow:hidden; padding:0; margin:0 auto;'>
			<center><img src='https://voicetrivia.com/static/system/email_hdr_img.jpg' 
			style='width:100%; display:block; background-size:cover; object-fit:cover' /></center>
		</div>
		<div class='clear'></div>
		<div style='border-bottom:2px solid #eee; margin:0 auto; max-width:60%;'></div>
		<div style='padding:15px; background:#fff; text-align:left;'>
			Hi,
			<br /><br />
			You received a new Offer on your Listing at VoiceTrivia.com.
			<br /><br />
			Visit https://voicetrivia.com/challenge/$id to view it...
			<br /><br />
			Thank you,
			<br /><br />
			- VoiceTrivia
			<br /><br />
			<center><span style='color:#aaa'>- - - - - - -</span>
			<br /><br />
			If you would like to stop receiving all emails from VoiceTrivia.com, simply click
			$unsubscribe - or you can also manage all your Unsubscribe Settings in the Notifications
			section on the Edit Account page at voicetrivia.com.</center>
		</div>
		<div class='clear'></div>
		</div>"; 	

		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

		$headers .= 'From: VoiceTrivia.com <noreply@voicetrivia.com>' . "\r\n";
		$headers .= 'Reply-To: VoiceTrivia.com <noreply@voicetrivia.com>';	
	
		@mail($receiver_email, $messageSubject, $msg, $headers, '-fnoreply@voicetrivia.com');			
	}
	    
	function exampleNotification(){
		// THE FUNCTIONS ARE READY TO GO
		if ($member['is_push'] == 1) {
			//require "api/webservices/functions.php";
			//$showtest = $this->test();
			//echo $showtest;

			//title, message, mediaurl, mediatype
			//$this->sendPush($to_token);
			//$this->sendPush($_POST['title'],$_POST['message'],$mediaurl, $mediatype,$to_token);
			//$this->sendPush($_POST['title'],$_POST['message'],$mediaurl, $mediatype,$to_token);
			//									echo $to_token ."<br />";
			//									echo $_POST['title'] ."<br />";
			//									echo $_POST['rawtext'] ."<br />";
			//									echo $mediaurl ."<br />";
			//									echo $mediatype ."<br />";

			//$this->sendMediaFCM($short_message,$message_title,$mediaurl,$to_token,$mediatype);
			//Function: $this->sendMediaFCM($message,$title,$imageUrl,$push_token,$mediaType);
			//print_r($show);
			//echo $show;
			//echo "Send a Rich Push Notification..." . $to_token . "<br /><br />";
			$push++;
		}
		
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
		// .'Content-type: text/html; charset=utf-8' . "\r\n"

		$headers .= 'From: ChattrBox <noreply@chattrboxx.com>' . "\r\n";
		$headers .= 'Reply-To: ChattrBox <noreply@chattrboxx.com>';
		//$headers .= 'Cc: thinappdev@gmail.com' . "\r\n";

		$email_recipient = $member;

		$welcome_email_title = "New Message Notification!";
		// <img src='https://app.ihphysicians.com/static/images/ihp_email_banner.png' alt='IHP' style='width:100%; height:auto;' />
		$welcome_email_body_OLD = "
								<br /><br />
								Hi,
								<br /><br />

								Thank you,<br />
								- ChattrBox Notifications";
		$welcome_email_body = $_POST['message'];

		//@mail($email_recipient, $email_title, $email_body, $headers, '-fappsupport@ihphysicians.com');
		//@mail($email_recipient, $welcome_email_title, $welcome_email_body, $headers, '-fcontact@igy6app.com');
		
		echo $push . " Rich Push Notifications sent!";		
	}   
	
	// SMS TEXT MESSAGE FUNCTION 
	
		function sendXXX() {
		if (!$_SESSION['user_id']) {
			die("Error: not logged in");
		}
		
		$messagesModel = new messagesModel();
		$squareusersModel = new squareusersModel();
		
		$data = $_POST;
		
		$data['message'] = htmlspecialchars($data['message']);
		$msg_snippet = substr($data['message'],0,50) . "...";
		
		$receiver = $data['to'];
		$receiver_user = $squareusersModel->getUser(['id' => $receiver]);
		$receiver_email = $receiver_user['email'];
		$receiver_phone = $receiver_user['phone'];
		
		$data['from'] = $_SESSION['user_id'];
		//$data['message'] = htmlspecialchars($data['message']);
		//$from = 'Your Brand <'.$data['fremail'].'>';

		$messagesModel->insert($data);
		echo "ok";
		
		// LET'S SEND THE USER AN EMAIL NOTIFICATION
		$messageSubject = "You've received a new message on ChattrBoxx.com!";
		$messageBody = "They wrote:<br /><br />
		{$data['message']}<br />
		Login at https://chattrboxx.com/auth/login to check your messages.";

		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

		$headers .= 'From: YourBrand <noreply@chattrboxx.com>' . "\r\n";
		$headers .= 'Reply-To: YourBrand <noreply@chattrboxx.com>';	
	
		@mail($receiver_email, $messageSubject, $messageBody, $headers, '-fnoreply@chattrboxx.com');	
	
		// LET'S SEND THE USER A TEXT NOTIFICATION
		require_once realpath(dirname(__FILE__) . "/../3rdparty/twilio-php-master/Services") . "/Twilio.php";

		$AccountSid = "ACc33ee9aa71e9a841111c0f6ef976af61";
		$AuthToken = "774b5173cc5c1ba2b61ee20769888fa1";

		$client = new Services_Twilio($AccountSid, $AuthToken);

		$message = $client->account->messages->create(array(
			"From" => "+13128789582",
			"To" => $receiver_phone,
			"Body" => "You received a new message at YourBrand where they said: " . $msg_snippet . " You can login and check it at chattrboxx.com/auth/login",
		));		
	}
	
	// PUSH NOTIFICATION FUNCTIONS START HERE 
    
	//	// SEND Rich Push Notification(s)
	//	function getUserUDID($id, $message, $title, $imageUrl, $mediaType){
	//		$query=query("SELECT id, email, user_push_id FROM users where id='$id' LIMIT 1");
	//		//$query=query("SELECT * FROM device_tokens where udid='$udid' ORDER BY date_updated ASC");
	//		$result=isset($query['result'][0])?$query['result'][0]:null;
	//
	//		if ($result)
	//			//print_r($result);
	//		return sendMediaFCM($message,$title,$imageUrl,$result['user_push_id'],$mediaType);
	//	}  
	
	// $this->sendPush($_POST['title'],$_POST['message'],$mediaurl, $mediatype,$to_token);
	// function sendPush($title, $message, $mediaurl, $mediatype, $push_token){
	function sendPush($push_token){
		$title = 'ChattrBox Bulk Notifications';
		$message = 'Check out the brand-new ChattrBox Notify App, which makes it easy for businesses and marketers to send bulk messages and notifications to large groups of users instantly. Learn more at chattrboxx.com';
		// MEDIA ATTACHMENT
		//$imageUrl = 'https://chattrboxx.com/static/images/rich_push_img.jpg'; // IMAGE PUSH
		$imageUrl = 'https://chattrboxx.com/api/push/media/nyc45.mp4'; // VIDEO PUSH
		$mediaType = "urlVideoString";

		//$mediaType = "urlImageString";
		//$mediaType = 'urlImageString' => $imageUrl,	
		
		$this->sendMediaFCM($message,$title,$imageUrl,$push_token,$mediaType);
		
		//$this->sendMediaFCM($message,$title,$imageUrl,$push_token,$mediaType);	
	}	  
    
    // SEND PUSH NOTIFICATION
	function sendMediaFCM($message, $title, $imageUrl, $registrationIds, $mediaType){
		$key="AAAAWeivm0A:APA91bGUNjX2kPdhUrUsD8pUo1Gvy-OuphEZKn8_R9t5URidB9pq2ckoQKYIp-FpN-HxnEu1Fo1qPoLFF5g0PFUfmXV3VeXSJF9D-KlnIiC-UpucSfJPHUnqlAQ1I9HmWDgfiJXUGe0G"; // ChattrBox Token

		$url = 'https://fcm.googleapis.com/fcm/send';

		$dataArray = array(
		//"message"=>$message,
		//"title"=>$title,
		"$mediaType" => $imageUrl,
		);

		// $dataArray["urlImageString"] = $imageUrl;

		//$dataArray["urlVideoString"] = $videoUrl;

		//print_r($imageUrl);

		$fields = array (
		'priority' => 'high',
		'to' => $registrationIds,
		'content_available' => true,
		'mutable_content' => true,
		'notification' => array(
		"body" => $message,
		"title" => $title,
		"vibrate" => 1,
		"sound" => 1,
		"badge" => 1,
		),
		'data' => $dataArray,
		//'category'=> "videoPush",
		//'category'=> "imagePush",
		//  'data' => array("urlVideoString"=>$videoUrl)
		);

		//	    $fields1 = json_encode ($fields);
		//		print_r($fields1);
		//		 exit;

		$headers = array(
		'Authorization: key=' . $key,
		'Content-Type: application/json',
		'apns-push-type: alert',
		'apns-priority: 10'
		);
	/*
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_POST, true );
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $body);*/

		$ch = curl_init();
		curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
		curl_setopt( $ch,CURLOPT_POST, true );
		curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
		curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
		curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode($fields));

		$result = curl_exec ( $ch );
		curl_close ( $ch );

		return $result;
	}    
	
	function enternow(){
			if (empty($_POST['uid']) || empty($_POST['pid']))
				exit;

			// GET IP ADDRESS
			// https://stackoverflow.com/questions/15699101/get-the-client-ip-address-using-php
			$ipaddress = '';
			if (isset($_SERVER['HTTP_CLIENT_IP']))
				$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
			else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
				$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
			else if (isset($_SERVER['HTTP_X_FORWARDED']))
				$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
			else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
				$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
			else if (isset($_SERVER['HTTP_FORWARDED']))
				$ipaddress = $_SERVER['HTTP_FORWARDED'];
			else if (isset($_SERVER['REMOTE_ADDR']))
				$ipaddress = $_SERVER['REMOTE_ADDR'];
			else
				$ipaddress = 'UNKNOWN';
			
			$user_id    = $_POST['uid'];
			$listing_id = $_POST['pid'];
			
//			echo json_encode($_POST);
//			exit;

			$db = Mysql::getInstance();
			// OK, NOW WE ENTER THEM
			$checkEntry = $db->insert("flipmobentries", [
					'prj' 			=> $listing_id,
					'user_id' 		=> $user_id,
					'name' 			=> $_SESSION['user']['name'],
					'ip_address' 	=> $ipaddress,
					'date'  		=> date("Y-m-d H:i:s")
				]
			);	
			$challengesModel = new challengesModel();
			$challengesModel->incrementETotal($listing_id, $user_id);
			
			// Need to also deduct user's credits

			if ($checkEntry) {
				echo 1;
				exit;
			} else {
				echo 0;
				exit;	
			}
	}
		
}	