<?php
// THIS CONTROLS THE HOST CHALLENGES
//error_reporting(1);
//ini_set('display_errors', 1);
//@ini_set('display_errors', 1);
//ini_set('display_errors', 'On');

// 0 - "created", poster/seller
// 1 - "hired", poster/seller
// 2 - "accepted", technically flipmobber/buyer, but we're merging 1 & 2
// 3 - "completed", poster/seller
// 4 - "reviewed", techically flipmobber/buyer
// 5 - "withdrawn - when escrow is released
// 6 - "rejected" - do we need a new status for rejected?

class solutionModel extends baseModel {
    const INVITE_PENDING  = 0;
    const INVITE_DENIED   = 1;
    const INVITE_ACCEPTED = 2;

	const TYPE_EVENT   	  = 1; // was CAMPAIGN - Now LISTING
    const TYPE_JOB 		  = 2; // BUYERS LOOKING FOR PROVIDERS was DEVSHARES LISTINGS, GET OFFERS/QUOTES
	const TYPE_DEAL 	  = 3; // SELLING/SELLERS LOOKING FOR BUYERS
    const TYPE_QUESTION	  = 4;
    const TYPE_BLOG		  = 5;
	const TYPE_CAMPAIGN	  = 6; // THIS SHOULD BE THE GOAL-BASED 
	const TYPE_PRODUCT	  = 7;
	const TYPE_OPINION	  = 8;
    const TYPE_SPACES 	  = 11;	
	const TYPE_STATUS	  = 12;	

	public $userImageFolder = "/static/images/users/agency/";
	
	static public $fields = [
		'project_type_id',
		'title',
		'description',
		'location',
		'location_lat',
		'location_lng',
		'user_id',
		'reviews_goal',
		'reviews_submitted',
		'reviews_unlocked',
		'category_id',
		'timestamp_end',	
		'main_img',
		'is_featured',
		'views',
		'host',
		'paypal_email',
		'tamount',
		'status',
		'budget',
		'terms',
		'is_private',
		'specific_fee',
		'already_paid',
		'redeem_type',
		'redeem_max',
		'redeem_max_global',
		'is_active',
		'original_main_img',
		'price',
		'date_to',
		'date_from',
		'menu',
		'chef_user_id',
		'facilitator_user_id',
		'location2',
		'location_lat2',
		'location_lng2',
		'locspec',
		'type_id',
		'tags',
		'pm',
		'pm_notes',
		'qat',
		'qat_notes',
		'simple',
		'chip_ins',
		'crowdfund',
		'budgetcf',
		'raised',
		'phone',
		'email',
		'quickmatch',
		'opportunity',
		'roi',
		'collab',
		'fmeligible',
		'entries',
		'allowed',
		'multi',
		'prize'
	];
	
//	static public $fields = [
//		'title','description','terms','location','location_lat','location_lng','paypal_email', 'category_id',
//		'reviews_goal', 'timestamp_end', 'is_featured','is_topcat','views',
//		'status', 'budget', 'terms', 'is_private', 'main_img',
//		'specific_fee', 'already_paid', 'redeem_type',
//		'redeem_max', 'is_active', 'project_type_id','price','type_id',
//		'date_to','date_from','period','size','user_id','location2','location_lat2','location_lng2'
//	];

    function test(){
        echo "Blog Test Model works. class blogModel extends baseModel {";
    }

	function fetchProject(&$project){
    	$this->db->where('id = ?', $project['user_id']);
		$project['user'] = $this->db->select('users')[0];
		//print_r($project['user']);

		//$this->db->where('user_id=?', $project['user']['id']);
		//$project['user']['avg_rating_given'] = round($this->db->select('reviews', 'AVG(rating) AS r')[0]['r'], 1);	
		
		// Added July 6 - Average Proposal Amount Received
		//$this->db->where('user_id=?', $project['user']['id']);
		//$project['user']['avg_proposal_amount'] = round($this->db->select('reviews', 'AVG(amount) AS a')[0]['a'], 1);
		
		// Added Oct 2023 - Average Proposal Amount Received
		$this->db->where('project_id=?', $project['id']);
		$project['avg_proposal_amount'] = round($this->db->select('proposals', 'AVG(amount) AS a')[0]['a'], 1);

		if ($project['user']['image'] && !strstr($project['user']['image'], '//')) {
			$project['user']['image'] = $this->userImageFolder . $project['user']['image'];
		}

		$this->db->where('project_id=?', $project['id']);
		$this->db->where('type=?', 'image');
		$project['images'] = $this->db->select('uploads');

		$this->db->where('project_id=?', $project['id']);
		$this->db->where('type != ?', 'image');
		$project['files'] = $this->db->select('uploads');

		$project['days_to_end'] = round((strtotime($project['timestamp_end']) - time()) / 86400);

		//$this->db->where('project_id=?', $project['id']);
		//$project['avg_rating'] = round($this->db->select('reviews', 'AVG(rating) AS r')[0]['r']);

		// Added July 6 - Average Proposal Amount Received
		//$this->db->where('project_id=?', $project['id']);
		//$project['avg_amount'] = round($this->db->select('reviews', 'AVG(amount) AS a')[0]['a']);

		$this->db->where('id=?', $project['category_id']);
		$project['category'] = $this->db->select('categories');
		
		// COMMENTS AND SUBCOMMENTS
		$this->db->where('project_id=?', $project['id']);
		$this->db->order_by('date_created DESC');
		$project['comments'] = $this->db->select('comments');
//		echo "<pre>";
//		print_r($project['comments']);
//		exit;
		foreach ($project['comments'] as $i => $comment) {
			$this->db->where('id = ?', $comment['user_id']);
			$project['comments'][$i]['user'] = $this->db->select('users')[0];

			if ($project['comments'][$i]['user']['image'] && !strstr($project['comments'][$i]['user']['image'], '//'))
				$project['comments'][$i]['user']['image'] = $this->userImageFolder . $project['comments'][$i]['user']['image'];
		}
		// COMMENTS TOTAL
		$this->db->where('project_id=?', $project['id']);
		$project['comments_count'] = $this->db->select('comments', "COUNT(*) AS c")[0]['c'];  

		$this->db->where('project_id=?', $project['id']);
		$this->db->order_by('sort ASC');
		$project['backing'] = $this->db->select('backing'); // Line 343 below is the Edit function
		foreach ($project['backing'] as $i => $requirement) {
			if (!empty($requirement['cf_id'])) {
				$this->db->where('id = ?', $requirement['cf_id']);
				$project['backing'][$i]['user'] = $this->db->select('users',['name','first_name','user_slug','image'])[0];	
			}
		}
//
//		$this->db->where('item_id=?', $project['id']);
//		$project['backed_amount'] = $this->db->select('backing_history', "SUM(amount) AS amount")[0]['amount'];
//
//		$this->db->where('item_id=?', $project['id']);
//		$project['backers'] = $this->db->select('backing_history', "COUNT(*) AS amount")[0]['amount'];

    	$project['proposals'] = $this->getProposals($id, $_SESSION['user']['id']);
    	//$project['redeems']   = $this->getRedeems(['project_id' => $id]);

//    	$campaignModel = new campaignModel();
//    	$project['campaign'] = $campaignModel->get(['project_id' => $project['id']]);
    	
    	// COMMENTS
//		$this->db->where('project_id=?', $project['id']);
//		$this->db->order_by('date_created DESC');
//		$project['comments'] = $this->db->select('comments');
//		foreach ($project['comments'] as $i => $comment) {
//			$this->db->where('id = ?', $comment['user_id']);
//			$project['comments'][$i]['user'] = $this->db->select('square_users')[0];
//
//			if ($project['comments'][$i]['user']['image'] && !strstr($project['comments'][$i]['user']['image'], '//'))
//				$project['comments'][$i]['user']['image'] = $this->userImageFolder . $project['comments'][$i]['user']['image'];
//		} 
		
		// TALENTS / SKILLS
		$this->db->where("project_id = ?", $project['id']);
		$tfields = [
			"project_talents.*",
			"(select title from talents where id = project_talents.talent_id) as title"];
		$talents = $this->db->select("project_talents", $tfields);
		$project['talents_ids'] = [];
		$project['talents']     = [];
		foreach ($talents as $ptalent) {
			$project['talents_ids'][] = $ptalent['talent_id'];
			$project['talents'][]     = $ptalent['title'];
		}
		
		// CHIP-INS 
		$this->db->where('project_id=?', $project['id']);
//		if ($_SESSION['loggedin'] || $_SESSION['user']['id']) {
//			//ORDER BY FIELD(id,1,5,4,3)
//			$this->db->order_by("case when user_id = {$_SESSION['user']['id']} then 0 else 1 end, id ASC");
//			//$this->db->order_by('user_id ASC');
//		}
		$this->db->order_by('id DESC');
		$project['chipins'] = $this->db->select('project_cofund');
		
		// VOTES (FOR THE LOGGED USER)
		if ($project['project_type_id']==2) {
			if ($_SESSION['loggedin'] || $_SESSION['user']['id']) {
				$this->db->where('prj=?', $project['id']);
				$this->db->where('user_id=?', $_SESSION['user']['id']);
				$project['votes'] = $this->db->select('flipmobentries', "COUNT(*) AS c")[0]['c'];
			} else {
				$project['votes'] = 0;
			}	
		} 
		
		// FAVORITES
		$this->db->where('object_id=?', $project['id']);
		$project['favs'] = $this->db->select('user_favorites', "COUNT(*) AS c")[0]['c'];  	
		
		foreach ($project['chipins'] as $i => $chipin) {
			$this->db->where('id = ?', $chipin['user_id']);
			$project['chipins'][$i]['user'] = $this->db->select('users')[0];
			//$project['chipins'][$i]['user'] = $this->db->select('users','image,name')[0];

			if ($project['chipins'][$i]['user']['image'] && !strstr($project['chipins'][$i]['user']['image'], '//'))
				$project['chipins'][$i]['user']['image'] = $this->userImageFolder . $project['chipins'][$i]['user']['image'];
		}
		
//		echo "<pre>";
//		print_r($project['chipins']);
//		exit;

		// CHIP-INS TOTAL
		$this->db->where('project_id=?', $project['id']);
		$project['chipinstotal'] = $this->db->select('project_cofund', "COUNT(*) AS c")[0]['c'];

		// POTENTIAL CROWD-FUNDING
		$this->db->where('project_id=?', $project['id']);
		$project['crowdfunding'] = $this->db->select('project_cofund', "SUM(rating) AS rating")[0]['rating'];       	
	}

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

		if (!is_numeric($id)) {
			return -1;
		}
		$this->db->where('id = ?', $id);
		$project = $this->db->select('projects')[0];
		
//		echo "<pre>";
//		print_r($project);

		if ($project)
            $this->fetchProject($project);

		return $project;
	}

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

		$this->db->where('is_featured & ' . FLAG_STAFFPICK, null);
		$this->db->order_by('RAND()');
		$project = $this->db->select('projects', 'id')[0];

		return $this->get($project['id']);
	}
	function addAmountPaid($id, $amount) {
		$this->db->query("UPDATE projects SET already_paid=already_paid+$amount WHERE id=$id");
	}
	function getTotalCount() {
		return $this->db->select('projects', 'COUNT(*) AS c')[0][c];
	}

	function setFeaturedFlag($id, $flag) {
		$this->db->query("UPDATE projects SET is_featured = is_featured | $flag WHERE id=$id");
	}

	function unsetFeaturedFlag($id, $flag) {
		$this->db->query("UPDATE projects SET is_featured = is_featured & ~$flag WHERE id=$id");
	}

    // #####################################
    // EDIT A NEW CONTENT ITEM 
    // #####################################
    
	function update($id, $data) {
		global $website_options;

		$update_data = $data;

		if (isset($data['duration'])) {
			$data['timestamp_end'] = date('Y-m-d H:i:s', time()+(86400*$data['duration']));
		}
		
		$this->saveTalentsForProject($id, $update_data['talents']);
		
		// GET AND UPDATE TALENTS/SKILLS
//		$this->db->where("project_id = ?", $id);
//		$tfields = [
//			"project_talents.*",
//			"(select title from talents where id = project_talents.talent_id) as title"];
//		$existing_talents = $this->db->select("project_talents", $tfields);
//		
//		$project['talents_ids'] = [];
//		foreach ($existing_talents as $ptalent) {
//			$project['talents_ids'][] = $ptalent['talent_id'];
//		}
		
//		echo "<pre>";
		//print_r($existing_talents);
//		print_r($project['talents_ids']);
//		exit;
		
//		foreach ($update_data['talents'] as $current_talent) {
//			//echo $current_talent . "<br />";
//			if (!in_array($current_talent,$project['talents_ids'])) {
//				// IS IN THE ARRAY 
//				//echo $current_talent . " is in the array<br />";
//				// IF IT'S NOT IN THE ARRAY THEN INSERT IT
//				echo $current_talent . " is NOT in the array, so let's insert it!<br />";
//			}
//		}
		//exit;
		
//		echo "<pre>";
//		print_r($talents);
//		exit;
		
		
		//print_r($update_data['talents']);
		//exit;

		foreach ($update_data as $index => $value) {
			if (!in_array($index, self::$fields)) {
				unset($update_data[$index]);
			}
			elseif (!empty($website_options['project_amount_fee']) && $index == "budget") {
				// APPLY FEE
				$update_data['budget'] = $value + ($value * ($website_options['project_amount_fee'] / 100));
			}
		}

		$this->db->where('id=?', $id)->update('projects', $update_data);

		$uploadsModel = new uploadsModel();
		if (!empty($data['files'])) {
			foreach ($data['files'] as $file) {
				$file = $uploadsModel->select($file);
				if (!empty($file)) {
					$uploadsModel->update($file['id'], [
						'project_id' => $id
					]);
				}
				if ($file['type'] == 'image' && $main_img == '') {
					$main_img = $file['file'];
				}
			}
		}
		if ($main_img) {
			$this->db->where('id = ?', $id);
			$this->db->update('projects', ['main_img' => $main_img]);
		}

		$this->db->where('project_id=?', $id);
		$this->db->delete('backing');
		
//		echo "<pre>";
//		print_r($_POST); 
 		
 		// Saves new lines and deletes Req Lines where Sort is 0
		foreach ($_POST['sort'] as $index => $amount) {
			// $amount is the sort values
			//echo "<pre>";
			//print_r($amount);

			if ($amount > 0) {
//				if ($amount < 99) {
//					$accepted = 1;
//				} else {
//					$accepted = 0;
//				}
				$accepted = $amount == 99 ? 0 : 1;
				//echo $accepted . "<br />";
				//echo "id: " . $id . " insert " . $amount . " and " . $accepted . "<br />";
				//echo $_POST['sort'][$index] . "<br />";
				
				// Accepted	
				$this->db->insert('backing', [
					'project_id' => $id,
					'sort' => $_POST['sort'][$index],
					'quantity_desired' => $_POST['back_quantity'][$index],
					'amount' => $_POST['amount'][$index],
					'reward' => htmlspecialchars($_POST['back_reward'][$index]),
					'eta' => htmlspecialchars($_POST['back_eta'][$index]),
					'days' => htmlspecialchars($_POST['days'][$index]),
					'cf_id' => $_POST['cf_id'][$index],
					'approved' => $accepted
				]);
			} 
		}

		$this->db->where('id=?', $id);
		$project = $this->db->select('projects')[0];
		if (!file_exists($project['main_img'])) {
			$this->db->where('project_id=?', $id);
			$this->db->where('type=?', 'image');
			$img = $this->db->select('uploads')[0];

			$this->db->where('id = ?', $id);
			$this->db->update('projects', ['main_img' => $img['file']]);
		}
	}

	function delete($id) {
		$this->db->where('id=?', $id);
		$this->db->delete('projects');

		$this->db->where('project_id=?', $id);
		$this->db->delete('reviews');

		$this->db->where('project_id=?', $id);
		$this->db->delete('uploads');
	}
	 
	function deletecofunder($cf_id) {
		$this->db->where('id=?', $cf_id);
		//$this->db->delete('chipins');
		$this->db->delete('project_cofund');
	}
	
	function deleteOffer($id) {
		$this->db->where('id=?', $id);
		//$this->db->delete('chipins');
		$this->db->delete('proposals');
	}
	
	function escrowOffer($id){
		$this->db->where('id = ?', $id);
		$offer = $this->db->select('proposals')[0];
		return $offer;
	}
	
	function reduceBalance($user_id,$offerAmount){
		$this->db->query("UPDATE users SET virtual_balance=virtual_balance-$offerAmount WHERE id='{$user_id}'");
		return 1;
	}
	
	function setEscrow($offer_id){
		// Reduce the User's balance
		
		// Set escrow for the offer to 1
		$this->db->query("UPDATE proposals SET escrow=1 WHERE id='{$offer_id}'");
		return 1;
	}

	function deleteFile($file_id, $project_id) {
		$this->db->where('id=?', $file_id);
		$this->db->where('project_id=?', $project_id);
		$file = $this->db->select('uploads')[0];

		if ($file) {
			unlink($file['file']);
		}

		$this->db->where('id=?', $file_id);
		$this->db->where('project_id=?', $project_id);
		$this->db->delete('uploads');

		$this->db->where('id=?', $project_id);
		$project = $this->db->select('projects')[0];

		if (!file_exists($project['main_img'])) {
			$this->db->where('project_id=?', $project_id);
			$this->db->where('type=?', 'image');
			$img = $this->db->select('uploads')[0];

			if (!empty($img['file'])) {
				$this->db->where('id = ?', $project_id);
				$this->db->update('projects', ['main_img' => $img['file']]);
			}
		}
	}

	function getRecentReviewers($project_id) {
		$this->db->where('project_id=?', $project_id);
		$this->db->order_by('timestamp DESC');
		$this->db->join('users', 'users.id = reviews.user_id');
		$r = $this->db->select('reviews');

		foreach ($r as $index => $review) {
			if ($review['image'] != '' && !strstr($review['image'], '//')) {
				$r[$index]['image'] = $this->userImageFolder . $review['image'];
			}
		}

		return $r;
	}

	function submitReview($post, $project_id) {
		$this->db->insert('reviews', [
			'project_id' => $project_id,
			'text' => $post['review'],
			'amount' => $post['amount'],
			'user_id' => $_SESSION['user_id'],
			'rating' => $post['rating'],
		]);

		$this->db->where('id=?', $project_id);
		$project = $this->db->select('projects')[0];	

		$this->db->insert('notifications', [
			'user_id' => $project['user_id'],
			'from_user_id' => $_SESSION['user_id'],
			'text' => "<a href='/challenge/{$project['id']}'>{$_SESSION['user']['name']} has submitted a comment/proposal on {$project['title']}</a>"
		]);

		$this->db->query("UPDATE users SET reviews_count=reviews_count+1 WHERE id='{$_SESSION['user_id']}'");
		$this->db->query("UPDATE projects SET reviews_submitted=reviews_submitted+1 WHERE id=$project_id");
	}	
	// NEW PROJECT REQUIREMENT REQUEST / SUGGESTION
	function submitReq($data){
		if (empty($data["cf_id"]) || empty($data['project_id']) || empty($data['reward']))
			return false;

		date_default_timezone_set('CDT');
		date_default_timezone_get();

		$cst_time = date("Y-m-d H:i:s", strtotime('0 hours'));

		$data['date_created'] = $cst_time;
		$data['approved'] = 0;

		$this->db->insert('backing', $data);
		//$c_id = $this->db->insert_id();

//		$this->db->where("id = ?", $data['project_id']);
//		$project = $this->db->select('projects')[0];
//
//		$this->db->where("id = ?", $data['user_id']);
//		$user  = $this->db->select('users')[0];
		
		//$this->db->query("UPDATE project SET comments_count = " . (((int) $project['comments_count']) + 1) . " WHERE id = " . $project['id']);
		//$this->db->query("UPDATE users SET comments_count = " . (((int) $user['comments_count']) + 1) . " WHERE id = " . $user['id']);

		//$sent_notifs = $this->notifyAboutComment($data['project_id'], $project['user_id'] , $data['user_id'], $data['content']);
		//$this->sendNotification($receiver_phone, $ver_code);
		//$this->sendNotification($project['phone'], $user['ver_code'],$project['email']);
		//getUserVerCode
		
//		$this->db->insert('backing', [
//			'project_id' => $data['project_id'],
//			'sort' => $data['sort'],
//			'quantity_desired' => $data['quantity_desired'],
//			'amount' => $data['amount'],
//			'reward' => htmlspecialchars($data['reward']),
//			'eta' => htmlspecialchars($data['eta']),
//			'days' => htmlspecialchars($data['days'])
//		]);	
		//return $c_id;
	}	

	function submitRating($data) {
		if (empty($data["review_id"]) || empty($data['project_id']) || empty($data['user_id']) || empty($data['submit_rating']))
			return false;
		
		$checkInsert = $this->db->insert("ratings", [
			'review' 		=> $data['review'],
			'project_id' 	=> $data['project_id'],
			'user_id' 		=> $data['user_id'],
			'rating'		=> $data['submit_rating'],
			'usertype'		=> $data['usertype'],
			'timestamp'		=> $data['timestamp'],
			'proposalid'	=> $data['review_id']
		]);
		return $checkInsert;
	}
	
	function submitProposalRating($data) {
		if (empty($data["review_id"]) || empty($data['project_id']) || empty($data['user_id']) || empty($data['submit_rating']))
			return false;
		
		$this->db->where('id=?', $data['review_id']);
		$this->db->update('proposals', ['rating' => $data['submit_rating']]);
	}
	
	function getBuyerRating($id){
		$usertype = "buyer";
		$this->db->where('project_id=?', $id);
		$this->db->where('usertype=?', $usertype );
		$buyerRating = $this->db->select('ratings')[0];
		if (!empty($buyerRating)) {
			return $buyerRating;
		}
	}
	
	function getSellerRating($id){
		$usertype = "seller";
		$this->db->where('project_id=?', $id);
		$this->db->where('usertype=?', $usertype );
		$sellerRating = $this->db->select('ratings')[0];
		if (!empty($sellerRating)) {
			return $sellerRating;
		}
	}	

	function submitRatingOLD($rating, $rating_id) {
		if (!is_numeric($rating) || !is_numeric($rating_id)) {
			return -1;
		}

		$this->db->where('reviews.id=?', $rating_id);
		$this->db->where('projects.user_id=?', $_SESSION['user_id']);
		$this->db->join('projects', 'projects.id=reviews.project_id');
		$review = $this->db->select('reviews', ['*', 'reviews.user_id AS review_user_id'])[0];

		if ($review && $review['rating'] == 0) {
			$this->db->where('id=?', $rating_id);
			$this->db->update('reviews', ['rating' => $rating]);
		}

		$this->db->query("UPDATE users SET credits=credits+$rating WHERE id='{$review['review_user_id']}'");
		$this->db->insert("credits", [
			'user_id' => $review['review_user_id'],
			'amount' => $rating,
			'type' => 'earned'
		]);
	}

	function unlockReview($review_id) {
		global $unlockPrice;

		$this->db->where('id=?', $review_id);
        $review = $this->db->select('reviews')[0];

        $userModel = new userModel();
        $review['user'] = $userModel->getUser($review['user_id']);

        if ($review) {
        	$this->db->where('id=?', $review['project_id']);
        	$project = $this->db->select('projects')[0];
        }

        if (!$review || !$project || $project['user_id'] != $_SESSION['user_id']) {
        	return -1;
        }

        if ($_SESSION['logged_in']) {
        	$this->db->where('review_id = ?', $review_id)
        		->db->where('project_id = ?', $project['id'])
        		->select('reviews_unlocked');

        	if ($this->db->affected_rows() > 0) {
        		$already_unlocked = 1;
        	}
        }

        $user = $userModel->getUser($_SESSION['user_id']);

        if (!isset($already_unlocked) || !$already_unlocked) {
	        if ($user['credits'] < $unlockPrice) {
	        	die("notenough");
	        }

			$this->db->query("UPDATE users SET credits=credits-$unlockPrice WHERE id={$_SESSION['user_id']}");
			$this->db->insert("credits", [
				'user_id' => $_SESSION['user_id'],
				'amount' => "-$unlockPrice",
				'type' => 'spent'
			]);

	        $this->db->insert('reviews_unlocked', [
	            'review_id' => $review_id,
	            'project_id' => $project['id'],
	        ]);

	        if ($this->db->affected_rows() == 1) {
	        	$this->db->query("UPDATE projects SET reviews_unlocked=reviews_unlocked+1 WHERE id={$project['id']}");
	        }
        }

        return $review;
	}

	function getUnlockedReviews($project_id) {
		$this->db->where('user_id=?', $_SESSION['user_id']);
		$this->db->where('id=?', $project_id);
		$p = $this->db->select('projects');

		if (count($p) != 1) {
			return [];
		}

		$this->db->join('reviews', 'reviews.id = reviews_unlocked.review_id');
		$this->db->join('users', 'reviews.user_id = users.id');
		$this->db->where("reviews_unlocked.project_id=?", $project_id);
		$r =  $this->db->select('reviews_unlocked');

		foreach ($r as $index => $review) {
			if ($review['image'] != '' && !strstr($review['image'], '//')) {
				$r[$index]['image'] = $this->userImageFolder . $review['image'];
			}
		}

		return $r;
	}

	function getReviews($project_id) {
		if (!is_numeric($project_id)) {
			return -1;
		}

		$this->db->where('project_id=?', $project_id);
		$this->db->join('users', 'reviews.user_id = users.id');
		$r = $this->db->select('reviews', ['*', 'reviews.id AS review_id']);

		foreach ($r as $index => $review) {
			if ($review['image'] != '' && !strstr($review['image'], '//')) {
				$r[$index]['image'] = "/static/images/users/agency/" . $review['image'];
			}
		}

		return $r;
	}

	function getList($cond = []) {
		//echo "Blog getList";
//		print_r($cond);
//		exit;
		global $website_options;
		
//		if (isset($cond['project_type_id'])) {
//			$this->db->where("project_type_id = ?", self::TYPE_STATUS);
//		}
		
		if (isset($cond['category_id'])) {
			$this->db->where('category_id=?', $cond['category_id']);
			//$this->db->where("is_active = ?", 1);
		}
		
        if (isset($cond['project_type_id']))
            $this->db->where('project_type_id=?', $cond['project_type_id']);
        		
		if (isset($cond['search'])) {
			$cond['search'] = strtolower($cond['search']);
			$this->db->where("lower(description) LIKE '%{$cond['search']}%' OR lower(title) LIKE '%{$cond['search']}%'", null);
		}
		if (isset($cond['is_featured'])) {
			$this->db->where("is_featured = ?", $cond['is_featured']);
		}
		if (isset($cond['user_id'])) {
			$this->db->where("projects.user_id = ?", $cond['user_id']);
		}
		if (isset($cond['status']))
			$this->db->where("status = ?", $cond['status']);

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

		if (isset($cond['is_active']))
			$this->db->where("is_active = ?", $cond['is_active']);
		
		// THE NEXT 5 THINGS BELOW ARE SPECIFICALLY FOR OUR NEARBY CONTENT ITEMS ADVANCED SEARCHING
		
		if (isset($cond['location']))
			$this->db->where("location LIKE ?", "%" . $cond['location'] . "%");

		if (!empty($cond['talents'])) {
        	$talents_condition = "(";
        	$i   = 0;
        	foreach ($cond['talents'] as $talent_id)
        		$talents_condition .= ($i++ > 0 ? " OR " : "") . "(exists (select true from project_talents where talent_id = {$talent_id} and project_id = projects.id))";
        	$talents_condition .= ")";

        	$this->db->where($talents_condition);
        }

        if (!empty($cond['types'])) {
        	$types_condition = "(";
        	$i = 0;
        	foreach ($cond['types'] as $type_id)
        		$types_condition .= ($i++ > 0 ? " OR " : "") . "projects.type_id = " . $type_id;
        	$types_condition .= ")";

			$this->db->where($types_condition);
        }

        if (!empty($cond['date_from']))
        	$this->db->where("date_from <= ?", $cond['date_from']);

        if (!empty($cond['date_to']))
        	$this->db->where("date_to >= ?", $cond['date_to']);		

		if (isset($cond['order']))
			$this->db->order_by($cond['order']);

		if (isset($cond['limit']))
			$this->db->limit = (int)$cond['limit'];

		if (!$_SESSION['loggedin'] || !$_SESSION['user']['id'])
			// return only publics !
			$this->db->where("is_private = 0", null);
		else {
			// get publics AND the ones the logged user is invited to.
			$user_id = isset($cond['user_id']) ? $cond['user_id'] : $_SESSION['user']['id'];
			$this->db->where("(
				is_private = 0
				OR projects.user_id = " . $user_id . "
				OR projects_invite.user_id = " . $user_id . ")", null);
			$this->db->join("projects_invite", "projects_invite.project_id = projects.id", "left");
		}

		// for fundraising, the date of end is important.
		$this->db->where("(projects.project_type_id != ? OR projects.timestamp_end > NOW())", self::TYPE_CAMPAIGN);

		// now check if we need to include distance.
		$fields = "projects.*";
		if ($cond['nearby_search']) {

			$fields   = "projects.*, (3959 * acos( cos(radians({$cond['latitude']})) * cos(radians(location_lat)) * cos(radians(location_lng) - radians({$cond['longitude']})) + sin(radians({$cond['latitude']})) * sin(radians(location_lat)) )) AS distance";
			$radius = !empty($cond['distance']) ? $cond['distance'] : 10;
			$having = "distance <= " . $radius;

			$this->db->order_by("distance ASC");
			//$this->db->having($having);
            if (!empty($radius))
                $this->db->having("distance <= {$radius}");			
		}
		$this->db->order_by("chip_ins DESC");
		$this->db->where('project_type_id=?', 2);
		$this->db->where('is_active=?', 1);
		$projects = $this->db->select('projects', $fields);

		foreach ($projects as $index => $row) {
			$this->db->where('id = ?', $row['user_id']);
			$projects[$index]['user'] = $this->db->select('users')[0];

			$projects[$index]['days_to_end'] = round((strtotime($row['timestamp_end']) - time()) / 86400);

			$this->db->where('project_id=?', $row['id']);
			$projects[$index]['avg_rating'] = round($this->db->select('reviews', 'AVG(rating) AS r')[0]['r']);
			
			//$this->db->where('object_id=?', $row['id']);
			//$projects[$index]['favs'] = $this->db->select('user_favorites', "COUNT(*) AS amount")[0]['amount'];

			$this->db->where('item_id=?', $row['id']);
			$projects[$index]['backed_amount'] = $this->db->select('backing_history', "SUM(amount) AS amount")[0]['amount'];
			$this->db->where('item_id=?', $row['id']);
			$projects[$index]['backers'] = $this->db->select('backing_history', "COUNT(*) AS amount")[0]['amount'];

			if (!$projects[$index]['main_img']) {
				$this->db->where('project_id=?', $row['id']);
				$this->db->where('type=?', 'image');
				$projects[$index]['images'] = $this->db->select('uploads');
				$projects[$index]['main_img'] = $projects[$index]['images'][0]['file'];
			}

        	$projects[$index]['proposals'] = $this->getProposals($row['id'],$_SESSION['user']['id']);
		}

		return $projects;
	}

    // #####################################
    // ADD A NEW CONTENT ITEM 
    // #####################################
    
	function insert($data) {
		global $website_options;
		
//		echo "<pre>";
//		print_r($data);
//		exit;
		
		$skills = $data['talents'];

//		foreach ($data as $index => $value) {
//			if (!is_array($value)) {
//				if ($index == 'description') {
//					// TODO: security
//					//$data[$index] = str_ireplace('<script>', '', $data[$index]);
//				}
//				else {
////					if (!empty($website_options['project_amount_fee']) && $index == "budget")
////						// APPLY FEE
////						$data['budget'] = $value + ($value * ($website_options['project_amount_fee'] / 100));
////					elseif (gettype($value) == 'string')
////						$data[$index] = htmlspecialchars($value);
//
//				}
//			}
//		}
		
//		print_r($data);
//		exit;
		
		$type = empty($data['project_type_id']) ? self::TYPE_JOB : $data['project_type_id'];

//		'project_type_id',
//		'title',
//		'description',
//		'location',
//		'location_lat',
//		'location_lng',
//		'user_id',
//		'reviews_goal',
//		'reviews_submitted',
//		'reviews_unlocked',
//		'category_id',
//		'timestamp_end',
//		'main_img',
//		'is_featured',
//		'views',
//		'host',
//		'paypal_email',
//		'tamount',
//		'status',
//		'budget',
//		'terms',
//		'is_private',
//		'specific_fee',
//		'already_paid',
//		'redeem_type',
//		'redeem_max',
//		'redeem_max_global',
//		'is_active',
//		'original_main_img',
//		'price',
//		'date_to',
//		'date_from',
//		'menu',
//		'chef_user_id',
//		'facilitator_user_id',
//		'location2',
//		'location_lat2',
//		'location_lng2'
// 'timestamp_end' => date('Y-m-d H:i:s', time()+(86400*$data['duration'])),
// 'timestamp_end' => date('Y-m-d H:i:s', $data['timestamp_end']),

		if (empty($data['location'])) {
			$location = "VoiceTrivia.com";
			//41.89287968768729, -87.62371763223203
		}
		if (empty($data['location_lat'])) {
			$location_lat = "41.89287968768729";
			//41.89287968768729, -87.62371763223203
		}
		if (empty($data['location_lng'])) {
			$location_lng = "-87.62371763223203";
		}
		
		$now = date('Y-m-d H:i:s');
		if (empty($data['timestamp_end'])) {
			$need_by = date('Y-m-d H:i:s', time()+(604800));		
			// 1 Week 604800 and 1 day 86400
		} else {
			$need_by = $data['timestamp_end'];
		}	

		$project_row = [
			'project_type_id' => $type,
			'title' => $data['title'],
			'description' => $data['description'],
			'location'=> $data['location'],
			'location_lat'=> $data['location_lat'],
			'location_lng'=> $data['location_lng'],
			'user_id' => $_SESSION['user']['id'],
			'reviews_goal' => $data['reviews_goal'],
			'reviews_submitted' => $data['reviews_submitted'],
			'reviews_unlocked' => $data['reviews_unlocked'],
			'category_id' => (int)$data['category_id'],
			'timestamp_end' => $need_by,
			'main_img' => $data['main_img'],
			'is_featured' => 1,
			'views' => 0,
			'host' => $_SESSION['user']['name'],
			'paypal_email' => '',
			'tamount' => $data['tamount'],
			'status' => 'created',
			'budget' => $data['budget'],
			'terms' => $data['terms'],
			'is_private' => $data['is_private'],
			'specific_fee' => 0,
			'already_paid' => 0,
			'redeem_type' => 'Single Use Coupon',
			'redeem_max' => 1,
			'redeem_max_global' => 1,
			'is_active' => 1, //$data['is_active']
			'original_main_img' => $data['main_img'],
			'price' =>  $data['price'],
			'date_to' => date('Y-m-d'),
			'date_from' => date('Y-m-d'),
			'menu' => '',
			'chef_user_id' => 1,
			'facilitator_user_id' => 1,
			'location2' => $data['location2'],
			'location_lat2' => $data['location_lat2'],
			'location_lng2' => $data['location_lng2'],
			'type_id' => $data['type_id'],
			'tags' => $data['tags'],
			'pm' => $data['pm'],
			'pm_notes' => $data['pm_notes'],
			'qat' => $data['qat'],
			'qat_notes' => $data['qat_notes'],
			'raised' => $data['raised'],
			'email' => $data['email'],
			'phone' => $data['phone'],
			'quickmatch' => $data['quickmatch'],
			'locspec' => $data['locspec'],
			'collab' => $data['collab'],
			'fmeligible' => $data['fmeligible'],
			'roi' => $data['roi'],
			'entries' => $data['entries'],
			'allowed' => $data['allowed'],
			'multi' => $data['multi'],
			'prize' => $data['prize'],
			'opportunity' => $data['opportunity']
		];
		
//		$project_row = [
//			'project_type_id' => 2,
//			'title' => 'Test',
//			'description' => 'Description...',
//			'location' => '59 W North Blvd Chicago, IL 60610',
//			'location_lat' => '111.00',
//			'location_lng' => '222.00',
//			'user_id' => 1,
//			'reviews_goal' => 0,
//			'reviews_submitted' => 0,
//			'reviews_unlocked' => 0,
//			'category_id' => 1,
//			'timestamp_end' => date('Y-m-d H:i:s', time()),
//			'main_img' => '',
//			'is_featured' => 1,
//			'views' => 0,
//			'host' => 'NA',
//			'paypal_email' => 'none@none.com',
//			'tamount' => 5000,
//			'status' => 'created',
//			'budget' => 5000,
//			'terms' => 'Terms...',
//			'is_private' => 0,
//			'specific_fee' => 0,
//			'already_paid' => 0,
//			'redeem_type' => 'Single Use Coupon',
//			'redeem_max' => 1,
//			'redeem_max_global' => 1,
//			'is_active' => 1,
//			'original_main_img' => '',
//			'price' => 5000,
//			'date_to' => date('Y-m-d'),
//			'date_from' => date('Y-m-d'),
//			'menu' => '',
//			'chef_user_id' => 1,
//			'facilitator_user_id' => 1,
//			'location2' => '605 N Michigan Ave Chicago, IL 60605',
//			'location_lat2' => '',
//			'location_lng2' => ''
//		];

//		if (! empty($data['redeem_type'])) {
//			// deals save
//			$project_row['redeem_type'] = $data['redeem_type'];
//			$project_row['redeem_max']  = 1;
//			if ($data['redeem_type'] == "Multi Use Coupon")
//				$project_row['redeem_max'] = 0;
//		}
		
//		print_r($project_row);
//		exit;

		$this->db->insert('projects', $project_row);
		
//		$record = $this->db->insert('projects', $project_row);
//		
//		print_r($record);
//		exit;

		$id = $this->db->insert_id();
		
		$this->saveTalentsForProject($id, $skills);

		$this->db->query("UPDATE users SET project_count=project_count+1 WHERE id='{$_SESSION['user_id']}'");

//		foreach ($data['back_amount'] as $index => $amount) {
//			if ($amount > 0) {
//				$this->db->insert('backing', [
//					'project_id' => $id,
//					'quantity_desired' => $data['back_quantity'][$index],
//					'amount' => $amount,
//					'reward' => htmlspecialchars($data['back_reward'][$index]),
//					'eta' => htmlspecialchars($data['back_eta'][$index])
//				]);
//			}
//		}

		$c = 0;
		$main_img = '';
		$uploadsModel = new uploadsModel();
		if (!empty($data['files'])) {
			foreach ($data['files'] as $file) {
				$file = $uploadsModel->select($file);
				if (!empty($file)) {
					$uploadsModel->update($file['id'], [
						'project_id' => $id
					]);
				}
			     if ($file['type'] == 'image' && $main_img == '') {
					//if ($file['data-type'] == 'image' && $main_img == '') {
					$main_img = $file['file'];
				}
			}
		}

		if ($main_img) {
			$this->db->where('id = ?', $id);
			$this->db->update('projects', ['main_img' => $main_img]);
		}

		return $id;
	}

	public function makeThumbnails()
	{
		$projects = $this->db->select('projects');
		foreach ($projects as $value) {
			if (empty($value['main_img'])) {
				continue;
			}

			resizeImg($value['main_img']);
		}

		return true;
	}

	function saveTalentsForProject($project_id, $talents)
	{
		$this->db->where("project_id = ?", $project_id);
		$this->db->delete("project_talents");

		foreach ($talents as $t_id) {
			// project_talents entry
			$this->db->insert("project_talents", [
				'talent_id' => $t_id,
				'project_id'  => $project_id]);
		}
	}

	function setProposalStatus($appointment_id, $status){
		if ($status==1) {
			$this->db->query("UPDATE proposals SET status={$status}, sel=1 WHERE id='{$appointment_id}'");
		} else {
			$this->db->query("UPDATE proposals SET status={$status} WHERE id='{$appointment_id}'");	
		}

		return $status;
	}
	
	function transferEscrow($offer_id, $member_id){
		
		// check escrow
		$this->db->where('id = ?', $offer_id);
		$offer = $this->db->select('proposals')[0];
		if ($offer['escrow']==1) {
			// then pay it out
			$escrowed_cents = $offer['amount'] * 100;
			$this->db->query("UPDATE users SET virtual_balance=virtual_balance+{$escrowed_cents}
			WHERE id='{$member_id}'");
			
			// LET'S SEND THE USER A TEXT NOTIFICATION
//			if ($receiver_phone != '') {
//				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" => "+13128789582",
//					"To" => $receiver_phone,
//					"Body" => "You received an escrow payment at VoiceTrivia.com. To unsubscribe to these notifications, visit https://voicetrivia.com/unsubscribe/".$ver_code,
//					));
//				} catch (\Exception $e) {
//					//return $e->getMessage();
//				}
//			}	
		}
	
	}
	
	// I THINK THIS JUST GETS THE LOGGED OR ACCEPTED USER'S OFFER/PROPOSAL
	function getProposalsOLD($project_id, $user_id = null) {
		global $website_options;

		if (!is_numeric($project_id)) {
			return -1;
		}

		if ($user_id != null)
			$this->db->where("proposals.user_id = ?", $user_id);

		$this->db->where('project_id=?', $project_id);
		$this->db->join('users', 'proposals.user_id = users.id');
		$this->db->order_by("`timestamp` DESC");
		$r = $this->db->select('proposals', ['*', 'proposals.id AS review_id']);

		foreach ($r as $index => $review) {
			if ($review['image'] != '' && !strstr($review['image'], '//')) {
				$r[$index]['image'] = "/static/images/users/agency/" . $review['image'];
			}

			// XXX add per-user fee settings
			if (!empty($website_options['proposal_amount_fee']))
				// APPLY FEE
				$r[$index]['amount'] = number_format(($r[$index]['amount'] + ($r[$index]['amount'] * ($website_options['proposal_amount_fee'] / 100))), 2);
		}

		return $r;
	}
	
	function getProposals($project_id, $user_id = null){
		global $website_options;

		if (!is_numeric($project_id)) {
			return -1;
		}
		if ($user_id != null)
			$this->db->where("proposals.user_id = ?", $user_id);
		
		$this->db->where('project_id=?', $project_id);
		$this->db->join('users', 'proposals.user_id = users.id');
		$this->db->order_by("`timestamp` DESC");
		$r = $this->db->select('proposals', ['*', 'proposals.id AS review_id']);

		foreach ($r as $index => $review) {
			if ($review['image'] != '' && !strstr($review['image'], '//')) {
				$r[$index]['image'] = "/static/images/users/agency/" . $review['image'];
			}

			// XXX add per-user fee settings
			if (!empty($website_options['proposal_amount_fee']))
				// APPLY FEE
			$r[$index]['amount'] = number_format(($r[$index]['amount'] + ($r[$index]['amount'] * ($website_options['proposal_amount_fee'] / 100))), 2);
		}

		return $r;
	}
	
	function submitProposal($post, $files, $project_id) {
		//global $website_options;

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

		$this->db->insert('proposals', [
			'project_id' => $project_id,
			'text' => $post['proposal'],
			'amount' => $post['amount'],
			'user_id' => $_SESSION['user_id']
		]);
		
		$proposal_id = $this->db->insert_id();

		$this->db->where('id=?', $project_id);
		$project = $this->db->select('projects')[0];

		$this->db->where("id = ?", $project['user_id']);
		$user  = $this->db->select('users')[0];

		// upload file.
		if (!empty($files['resume'])) {
			$ext 		 = strtolower(pathinfo($files['resume']['name'], PATHINFO_EXTENSION));
			$filename    = sprintf("proposal_%s_%s", $proposal_id, md5_file($files['resume']['tmp_name']));
			$destination = "static/uploads/projects/$filename.$ext";
			if (!file_exists($destination))
				move_uploaded_file($files['resume']['tmp_name'], $destination);

			$uploadsModel = new uploadsModel();
			$u_id = $uploadsModel->insert($destination, 'document', $files['resume']['name']);

			$this->db->where("id = ?", $proposal_id);
			$this->db->update("proposals", ['id_upload' => $u_id]);
		}
	
		$this->db->insert('notifications', [
			'user_id' => $project['user_id'],
			'from_user_id' => $_SESSION['user']['id'],
			'text' => "<a href='/challenge/{$project['id']}'>{$_SESSION['user']['name']} has submitted a comment/proposal on {$project['title']}</a>"
		]);
 
			//print_r($project['phone']);
			//print_r($project['email']);
			//print_r($user['ver_code']);
		
		//$this->sendNotif($project['phone'],$user['ver_code'],$project['email']);

	}	

	function submitProposalXXX($post, $files, $project_id) {
		global $website_options;

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

		$this->db->insert('proposals', [
			'project_id' => $project_id,
			'text' => $post['proposal'],
			'amount' => $post['amount'],
			'user_id' => $_SESSION['user_id']
		]);

		$proposal_id = $this->db->insert_id();

		$this->db->where('id=?', $project_id);
		$project = $this->db->select('projects')[0];
		
		$this->db->where("id = ?", $project['user_id']);
		$user  = $this->db->select('users')[0];

		// upload file.
		if (!empty($files['resume'])) {
			$ext 		 = strtolower(pathinfo($files['resume']['name'], PATHINFO_EXTENSION));
			$filename    = sprintf("proposal_%s_%s", $proposal_id, md5_file($files['resume']['tmp_name']));
            $destination = "static/uploads/projects/$filename.$ext";
            if (!file_exists($destination))
                move_uploaded_file($files['resume']['tmp_name'], $destination);

            $uploadsModel = new uploadsModel();
            $u_id = $uploadsModel->insert($destination, 'document', $files['resume']['name']);

            $this->db->where("id = ?", $proposal_id);
            $this->db->update("proposals", ['id_upload' => $u_id]);
		}

		$this->db->insert('notifications', [
			'user_id' => $project['user_id'],
			'from_user_id' => $_SESSION['user_id'],
			'text' => "<a href='/challenge/{$project['id']}'>{$_SESSION['user']['name']} has submitted a comment/proposal on {$project['title']}</a>"
		]);
		
		//$this->sendNotif($project['phone'],$user['ver_code'],$project['email']);
	}
	
	function sendNotif($receiver_phone, $ver_code, $receiver_email){
		
		// 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 Bid/Proposal 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 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
		if ($receiver_phone != '') {
			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" => "+13128789582",
				"To" => $receiver_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/".$ver_code,
				));
			} catch (\Exception $e) {
				//return $e->getMessage();
			}
		}	
		
//		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 Bid/Proposal at VoiceTrivia.com. Visit https://voicetrivia.com to view it. To unsubscribe to these notifications, visit https://voicetrivia.com/unsubscribe/".$ver_code,
//		));	
//		exit;
	}

	function getHiredCandidate($project_id) {
		$uid = $this->db->where("project_id = ?", $project_id)
						->where("sel = 1")
						->select_one("proposals", ['user_id']);

		if (empty($uid))
			// cannot find candidate
			return false;

		$userModel = new userModel();
		$user = $userModel->getUser($uid['user_id']);
		return $user;
	}

	function getHiredProposal($project_id) {
		$prop = $this->db->where("project_id = ?", $project_id)
						->where("sel = 1")
						->select_one("proposals");

		if (empty($prop))
			return false;

		return $prop;
	}

	function getProposal($proposal_id)
	{
		$this->db->where("id = ?", $proposal_id);
		$prop = $this->db->select_one("proposals");

		$userModel    = new userModel();
		$uploadsModel = new uploadsModel();

		$prop['project'] = $this->get($prop['project_id']);
		$prop['user']    = $userModel->getUser($prop['user_id']);

		if (!empty($prop['id_upload']))
			$prop['resume'] = $uploadsModel->select($prop['id_upload']);

		return $prop;
	}

	function setProjectStatus($project_id, $status){
		if (! in_array($status, array("created", "hired", "accepted", "completed", "reviewed", "withdrawn")))
			return false;

		$project = $this->get($project_id);
		if (empty($project))
			// wrong project id
			return false;

		$this->db->where("id = ?", $project_id);
		$this->db->update("projects", ['status' => $status]);

		$method = "post" . strtoupper($status);
		if (method_exists($this, $method))
			$this->$method($project_id);

		return true;
	}
	
	function acceptTheOffer($offer_id){
		$this->db->where('id=?', $offer_id);
		$this->db->update('proposals', ['status' => 1]);
		return true;
	}
	
	function updateOffer($data){
		$this->db->where('id=?', $data['id']);
		$this->db->update('proposals', $data);
	}

	function postAccepted($project_id)
	{
		$project   = $this->get($project_id);
		$proposal  = $this->getHiredProposal($project_id);
		$candidate = $this->getHiredCandidate($project_id);

		/* Notify Listing owner that the candidate ACCEPTED the offer ! */
		$this->db->insert('notifications', [
			'user_id' => $project['user_id'],
			'from_user_id' => $proposal['user_id'],
			'text' => "<a href='/challenge/{$project['id']}'>{$candidate['name']} has accepted the job on {$project['title']} !</a>"
		]);
	}

	function postCompleted($project_id)
	{
		$project   = $this->get($project_id);
		$proposal  = $this->getHiredProposal($project_id);
		$candidate = $this->getHiredCandidate($project_id);

		/* Notify project owner that the candidate COMPLETED the job ! */
		$this->db->insert('notifications', [
			'user_id' => $project['user_id'],
			'from_user_id' => $proposal['user_id'],
			'text' => "<a href='/challenge/{$project['id']}'>{$candidate['name']} has <b>completed</b> the job on {$project['title']} ! Please review and confirm that the user can Withdraw the funds.</a>"
		]);
	}

	function postReviewed($project_id)
	{
		$project   = $this->get($project_id);
		$proposal  = $this->getHiredProposal($project_id);
		$candidate = $this->getHiredCandidate($project_id);

		/* Notify candidate that the project owner REVIEWED the job ! */
		$this->db->insert('notifications', [
			'user_id' => $proposal['user_id'],
			'from_user_id' => $project['user_id'],
			'text' => "<a href='/challenge/{$project['id']}'>Your job on {$project['title']} was reviewed and confirmed by the project owner. You can now safely withdraw your funds.</a>"
		]);
	}

	function postWithdrawn($project_id)
	{
		global $website_options;

		$project   = $this->get($project_id);
		$proposal  = $this->getHiredProposal($project_id);
		$candidate = $this->getHiredCandidate($project_id);

		// REMOVE FEE, the fee should stay on the website owner paypal account !
		// to remove the fee, apply formula: amount / 1.13   (if fee = 13%)

		$proposal_fee       = $website_options['proposal_amount_fee'];
		$proposal['amount'] = number_format(($proposal['amount'] / ((float) ("1." . $proposal_fee))), 2);

		$userModel = new userModel();
		$users     = $userModel->getList();

 		foreach ($users as $user) {
 			if (empty($user['is_admin']))
 				continue;

			/* Notify admin that the funds must be released for the job ! */
 			$this->db->insert('notifications', [
				'user_id' => $user['id'],
				'from_user_id' => $proposal['user_id'],
				'text' => "<a href='/challenge/{$project['id']}'>{$project['title']} is done and the funds must now be released. The PayPal transfer of amount \${$proposal['amount']} must be done to PayPal account '{$candidate['paypal_email']}' !.</a>"
			]);
 		}
	}

	function submitCandidateRating($rating, $proposal_id) {
		if (!is_numeric($rating) || !is_numeric($proposal_id))
			return -1;

		$this->db->where('proposals.id=?', $proposal_id);
		$this->db->where('projects.user_id=?', $_SESSION['user_id']);
		$this->db->join('projects', 'projects.id=proposals.project_id');
		$proposal = $this->db->select('proposals', ['*', 'proposals.user_id AS proposal_user_id'])[0];

		if ($proposal && $proposal['rating'] == 0) {
			$this->db->where('id=?', $proposal_id);
			$this->db->update('proposals', ['rating' => $rating]);
		}
	}

    /**
     * @return integer (-1 = not invited ; 0 = pending ; 1 = denied ; 2 = accepted)
     **/
    function getInviteState($project_id, $user_id)
    {
        $this->db->where("project_id = ?", $project_id)
                 ->where("user_id = ?", $user_id);
        $result = $this->db->select_one("projects_invite", "state")['state'];

        if (empty($result) && $result !== '0')
        	return -1;

        return $result;
    }

    function inviteUser($project_id, $user_id)
    {
        $exists = $this->db->where("project_id = ?", $project_id)
                           ->where("user_id = ?", $user_id)
                           ->select_one("projects_invite");

        if (!empty($exists)) {
            $this->db->where("id=?", $exists['id']);
            $this->db->delete("projects_invite");
        }

        $project = $this->db->where("id = ?", $project_id)
                          ->select_one("projects");

        // needs insert
        $this->db->insert("projects_invite", array(
            "project_id" => $project_id,
            "user_id"  => $user_id,
            "state"    => projectModel::INVITE_PENDING));

        // now notify user
        $notifyModel = new notificationsModel();
        $notifyModel->insert(array(
            "user_id" => $user_id,
            "from_user_id" => $project['user_id'],
			"text" => sprintf("You are invited to the Project '%s'. <a class='btn btn-green' href='/challenge/acceptInvite/%s/%s'>View the Challenge.</a>", $project['title'], $project['id'], $user_id)
        ));

        return $this->db->insert_id();
    }

    function toggleJoin($project_id, $user_id)
    {
        // update project invites.
        $this->db->where("user_id = ?", $user_id)
                 ->where("project_id = ?", $project_id)
                 ->update("projects_invite", array("state" => 1));

        return true;
    }

    function saveDispute($project_id, $user_id, $message)
    {
    	$this->db->insert("projects_dispute", [
    		'project_id' => $project_id,
    		'user_id'    => $user_id,
    		'message'    => $message]);

        $userModel = new userModel();
        $project   = $this->get($project_id);
		$users     = $userModel->getList();

 		/* Notify admins that a dispute was filed ! */
 		foreach ($users as $admin) {
 			if (empty($admin['is_admin']))
 				continue;

 			$this->db->insert('notifications', [
				'user_id' => $admin['id'],
				'from_user_id' => $user_id,
				'text' => "<a href='/challenge/{$project['id']}'>A dispute has been filed for the project {$project['title']}. Please have a look at it !</a>"
			]);
 		}

 		/* Notify counterpart user that a dispute was filed AGAINST him. */
 		$candidate = $this->getHiredCandidate($project_id);
 		$this->db->insert('notifications', [
			'user_id' => $candidate['id'],
			'from_user_id' => $user_id,
			'text' => "<a href='/challenge/{$project['id']}'>A dispute has been filed against you for the project {$project['title']} !</a>"
		]);

    	return $this->db->insert_id();
    }

    function getDisputes($cond = [])
    {
    	if (isset($cond['project_id']))
    		$this->db->where("project_id = ?", $cond['project_id']);
    	if (isset($cond['user_id']))
    		$this->db->where("user_id = ?", $cond['user_id']);

    	$this->db->order_by("date_created DESC");
    	return $this->db->select("projects_dispute");
    }

    function getRedeems($cond = [])
    {
    	if (isset($cond['project_id']))
    		$this->db->where("project_id = ?", $cond['project_id']);
    	if (isset($cond['user_id']))
    		$this->db->where("user_id = ?", $cond['user_id']);

    	$this->db->order_by("date_created DESC");
    	return $this->db->select("deal_redeem");
    }

    function saveRedeem($pid, $uid)
    {
    	$userModel = new userModel();

    	// input validation
    	$project = $this->get($pid);
    	$user    = $userModel->getUser($uid);

    	if (empty($project) || empty($user))
    		return false;

    	$this->db->insert("deal_redeem", [
    		'user_id' 	 => $uid,
    		'project_id' => $pid]);
    	return $this->db->insert_id();
    }

    function getActiveDealsByUser($uid)
    {
    	return $this->getList([
    		'user_id' 	=> $uid,
    		'is_active' => 1]);
    }

    function addaView($id,$userip) {
        $this->db->insert("pageviews", [
            'page' => $id,
            'userip' => $userip
        ]);
    }
    
	function addaViewNew($id, $userip, $section){
        $this->db->insert("pageviews", [
            'page' => $id,
            'userip' => $userip,
            'section' => $section
        ]);
    }
    
    function getTotalUniqueViews($id) {
        $this->db->where('page=?', $id);
        return $this->db->select('pageviews', 'COUNT(DISTINCT(userip)) AS c')[0][c];
    }   
        
    function getTotalPageViews($id) {
        $this->db->where('page=?', $id);
        return $this->db->select('pageviews', 'COUNT(page) AS c')[0][c];
    }    
    
    // COMMENTS FEATURE 
	function postComment($data){
		if (empty($data["user_id"]) || empty($data['project_id']) || empty($data['content']))
			return false;

		date_default_timezone_set('CDT');
		date_default_timezone_get();
		
		$cst_time = date("Y-m-d H:i:s", strtotime('0 hours'));
		
		$data['date_created'] = $cst_time;
		
		$this->db->insert('comments', $data);
		$c_id = $this->db->insert_id();

		$this->db->where("id = ?", $data['project_id']);
		$project = $this->db->select('projects')[0];

		$this->db->where("id = ?", $data['user_id']);
		$user  = $this->db->select('users')[0];

		//$this->db->query("UPDATE project SET comments_count = " . (((int) $project['comments_count']) + 1) . " WHERE id = " . $project['id']);
		//$this->db->query("UPDATE users SET comments_count = " . (((int) $user['comments_count']) + 1) . " WHERE id = " . $user['id']);

		//$sent_notifs = $this->notifyAboutComment($data['project_id'], $project['user_id'] , $data['user_id'], $data['content']);
		//$this->sendNotification($receiver_phone, $ver_code);
		//$this->sendNotification($project['phone'], $user['ver_code'],$project['email']);
		//getUserVerCode
		return $c_id;
	}    
	
	function notifyAboutComment($project_id, $project_owner, $user_id, $content){
		//echo "Timezone : " . date_default_timezone_set('CDT');
		//echo date_default_timezone_get();
		date_default_timezone_set('CDT');
		date_default_timezone_get();
		/* Insert a Notification about the Comment ! */
		$this->db->insert('notifications', [
			'user_id' => $project_owner, // The user whose post it was
			'from_user_id' => $user_id, // The user making the comment
			'text' => "Someone just commented on your Challenge and wrote: {$content}. <a href='/challenge/{$project_id}'>Click here to see it...</a>"
		]);		
	}
	
	function sendNotification($receiver_phone, $ver_code, $receiver_email){
		
		// LET'S SEND THE USER AN EMAIL NOTIFICATION
		$messageSubject = "New Comment 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 comment on your Challenge 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 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 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,
		));	
	}
	
	function getComments($project_id){
		if (!is_numeric($project_id))
			return -1;

		$this->db->where('project_id=?', $project_id);
		$this->db->join('users', 'comments.user_id = users.id');
		$r = $this->db->select('comments', ['*', 'comments.id AS comment_id']);

		foreach ($r as $index => $review) {
			if ($review['image'] != '' && !strstr($review['image'], '//')) {
				$r[$index]['image'] = "/static/images/users/agency/" . $review['image'];
			}
		}

		return $r;
	}	
	
	function postChipin($data){
		if (empty($data["user_id"]) || empty($data['project_id']))
			return false;

		if (empty($data["comment"])) {
			$data["comment"] = "";
		}

		if (empty($data["rating"])) {
			$data["rating"] = 0;
			$contribution = 0;
		} else {
			$contribution = $data["rating"];
		}
		
		if ($data['escrow']==1) {
			$escrowAmt = $data["escrowAmt"];
		} else {
			//$escrowAmt = 0;
			$escrowAmt = $data["escrowAmt"];
		}

		$this->db->insert('project_cofund', $data);
		$co_id = $this->db->insert_id();

		// also update projects.contributions_count
		$this->db->where("id = ?", $data['project_id']);
		$project = $this->db->select('projects')[0];

		//$this->db->where("id = ?", $data['user_id']);
		//$user  = $this->db->select('users')[0];

		$this->db->query("UPDATE projects SET chip_ins = " . (((int) $project['chip_ins']) + 1) . ", crowdfund = " . (((int) $project['crowdfund']) + $contribution) . ", already_paid = " . (((int) $project['already_paid']) + $escrowAmt) . " WHERE id = " . $project['id']);
		
		// ONLY IF ESCROW IS CHECKED DO WE DEDUCT THE USER'S BALANCE
		if ($data['escrow']==1) { }
		// also update the user's virtual balance
		$this->db->where("id = ?", $data['user_id']);
		$user = $this->db->select('users')[0];

		//$contrCents = $data["escrowAmt"] * 100;
		$contrCents = $data["escrowAmt"]; // in cents

		//$_SESSION['user']['virtual_balance'] = $_SESSION['user']['virtual_balance'] - ($data["escrowAmt"] * 100);
		$_SESSION['user']['virtual_balance'] = $_SESSION['user']['virtual_balance'] - ($data["escrowAmt"]);
		$this->db->query("UPDATE users SET virtual_balance = " . (((int) $user['virtual_balance']) - $contrCents) . " WHERE id = " . $user['id']);
		
		
		//$this->db->query("UPDATE users SET comments_count = " . (((int) $user['comments_count']) + 1) . " WHERE id = " . $user['id']);

		//$sent_notifs = $this->notifyAboutComment($data['feature_id'], $data['user_id'], $data['content']);
		return $co_id;
	}	   
	
	function getRecent(){
		$this->db->order_by('id DESC');
		$this->db->where("is_active = ?", 1);
		$this->db->limit(7);
		$recent = $this->db->select('projects');

		return $recent;
	}
	
	function getFeaturedListings(){
		$this->db->order_by('RAND()');
		//$this->db->where("is_featured = ?", 1);
		$this->db->limit(4);
		$featuredListings = $this->db->select('projects');

		return $featuredListings;
	}
	
	function getUserVerCode($uid){
		$userModel = new userModel();
		$user    = $userModel->getUser($uid);

		if (empty($user))
			return false;

		return $user['ver_code'];
	}
	
	function updateContr($data){
		
		// NEED TO CONSIDER CHANGES IN ESCROW BEFORE WE UPDATE 
		$this->db->where("id = ?", $data['id']);
		$currPledge = $this->db->select_one("project_cofund");
		
//		$escrowChange = ($data['escrowAmt'] - $currPledge['escrowPrev'])*100;
		
//		echo json_encode($escrowCents);
//		exit;	
		
		$data['escrow'] = !empty($data['escrow']) ? 1 : 0;
		
		$this->db->where("id = ?", $currPledge['user_id']);
		$user = $this->db->select_one("users");

//		$this->db->where('id = ?', $data['user_id']);
//		$this->db->update('users', ['virtual_balance' => virtual_balance-$escrowCents]);
//		$data['escrowPrev'] = $data['escrowAmt'];	
		
		// need to eventually check if they try to reduce the pledge lower than the min required
		
		if($currPledge['escrow']==0 && $data['escrow']==1){
			// NEW ESCROW, SO ESCROW THE FULL AMOUNT/RATING
			// Now decrease the user's virtual_balance (ie. Account Balance)
//			$this->db->where('id = ?', $data['user_id']);
//			$this->db->update('users', ['virtual_balance' => virtual_balance-$data['escrowAmt']]);	
			$escrowCents = $data['escrowAmt'] * 100;
			$_SESSION['user']['virtual_balance'] = $_SESSION['user']['virtual_balance'] - $escrowCents;
			$this->db->query("UPDATE users SET virtual_balance = " . (((int) $user['virtual_balance']) - $escrowCents) . " WHERE id = " . $user['id']);
			$data['escrowPrev'] = $data['escrowAmt'];
			$escrowChange = $data['escrowAmt'];
		} elseif($currPledge['escrow']==1 && $data['escrow']==1){
			// ESCROW STAYS ON, BUT CHECK THE AMOUNTS
			$escrowChange = $data['escrowAmt'] - $currPledge['escrowPrev'];
			$escrowCents = $escrowChange * 100;
			$_SESSION['user']['virtual_balance'] = $_SESSION['user']['virtual_balance'] - $escrowCents;
			$this->db->query("UPDATE users SET virtual_balance = " . (((int) $user['virtual_balance']) - $escrowCents) . " WHERE id = " . $user['id']);
//			$this->db->where('id = ?', $data['user_id']);
//			$this->db->update('users', ['virtual_balance' => virtual_balance-$escrowChange]);	
			$data['escrowPrev'] = $data['escrowAmt'];	
		} elseif($currPledge['escrow']==0 && $data['escrow']==0){
			// NO ESCROW OR BALANCE CHANGES JUST UPDATE THE RECORD BELOW
			$data['escrowAmt'] = $currPledge['escrowAmt']; // make sure they can't over-ride it
			$escrowChange = 0;
		} elseif($currPledge['escrow']==1 && $data['escrow']==0){
			if ($data['escrowAmt'] == $currPledge['escrowAmt'] || $data['escrowAmt'] < $currPledge['escrowAmt']) {
				$escrowCents = $data['escrowAmt'] * 100;
				$_SESSION['user']['virtual_balance'] = $_SESSION['user']['virtual_balance'] - $escrowCents;
				$this->db->query("UPDATE users SET virtual_balance = " . (((int) $user['virtual_balance']) - $escrowCents) . " WHERE id = " . $user['id']);
				$data['escrowPrev'] = 0;
				$escrowChange = 0 - $data['escrowAmt'];
			} else {
				$escrowCents = $data['escrowAmt'] * 100;
				$_SESSION['user']['virtual_balance'] = $_SESSION['user']['virtual_balance'] - $escrowCents;
				$this->db->query("UPDATE users SET virtual_balance = " . (((int) $user['virtual_balance']) - $escrowCents) . " WHERE id = " . $user['id']);	
				$data['escrowAmt'] = 0;	
				$data['escrowPrev'] = 0;	
				$escrowChange = 0 - $data['escrowAmt'];	
			}
			// UNDO ESCROW, GIVE FUNDS BACK
		} else {
			// NO CLUE WHAT THIS IS...SO JUST UPDATE IT, WITH NO MAJOR BALANCE CHANGES
			$data['escrowAmt'] = $currPledge['escrowAmt'];
			$escrowChange = 0;
		}
		
		// AND UPDATE THE PREV AMOUNT WITH THE CURRENT AMOUNT TOO
		
		$this->db->where('id = ?', $data['id']);
		$this->db->update('project_cofund', $data);
		
		/////////////////////////////////////////////////////////////////////
		// and update the running totals in the projects table too
		$this->db->where('id = ?', $data['project_id']);
		$currentPRJ = $this->db->select_one('projects');
	
		// first, get the current crowdfund total
		$currentCF = !empty($currentPRJ['crowdfund']) ? $currentPRJ['crowdfund'] : 0;
		//$value = empty($value) ? "0" : "1";
		//$data['is_subscribe'] = !empty($data['is_subscribe']) ? 1 : 0;
		
		// then calculate the additional funds because of the change
		if ($data['rating'] == $data['prevamt']) {
			$additional = 0;
		} else {
			$additional = $data['rating'] - $data['prevamt'];	
		}
		
		$newCFAmt = $currentCF + $additional;
		
		// escrow running total
		$currentAP = !empty($currentPRJ['already_paid']) ? $currentPRJ['already_paid'] : 0;
		$newAPTot  = $currentAP + $escrowChange;
		
		// now update the crowdfund amount
		$this->db->where('id = ?', $data['project_id']);
		$this->db->update('projects', ['crowdfund' => $newCFAmt, 'already_paid' => $newAPTot]); // already_paid	
	}
	
	function updateContrwithEscrow($data){
		$this->db->where('id = ?', $data['id']);
		//$this->db->update('chipins', $data);
		$this->db->update('project_cofund', $data);

		// and update the running total in the projects table too

		// first, get the current crowdfund total
		$this->db->where('id = ?', $data['project_id']);
		$currentPRJ = $this->db->select_one('projects');

		// then calculate the additional funds because of the change
		$currentCF = $currentPRJ['crowdfund'];
		$additional = $data['rating'] - $data['prevamt'];

		$newCFAmt = $currentCF + $additional;

		// now update the crowdfund amount
		$this->db->where('id = ?', $data['project_id']);
		$this->db->update('projects', ['crowdfund' => $newCFAmt]);
		
		//////////////////////////////////////
		// HANDLE ESCROW NOW
		
		$additional = $data['rating'] - $data['escrowAmt'];
		
		if ($data['rating'] > $data['escrowAmt']) {
			$escrow_amount = $data['rating'] - $data['escrowAmt']; // increase by this amount
			
		} else if ($data['rating'] < $data['escrowAmt']) {
			$escrow_amount = $data['rating'] - $data['escrowAmt']; // reduce by this amount
		}
		
		// Now decrease the user's virtual_balance (ie. Account Balance)
		$this->db->where('id = ?', $data['user_id']);
		$this->db->update('users', ['virtual_balance' => virtual_balance+$escrow_amount]);				
	}

	function getpledge($id){
		$this->db->where("id = ?", $id);
		return $this->db->select_one("project_cofund");
	}
	
	function checkStatus($uid,$cid){
		$this->db->where("user_id = ?", $uid);
		$this->db->where("project_id = ?", $cid);
		$entry = $this->db->select_one("project_cofund");
		
		if (!empty($entry)) {
			return 1;
		} else {
			return 0;
		}
	}
	
	//$this->db->where("id = ?", $data['id']);
	//$currPledge = $this->db->select_one("project_cofund");
	
	function updateMultiOffer($data){
		$this->db->where('id = ?', $data['id']);
		$this->db->update('project_cofund', $data);
	}
	// THESE NEXT FUNCTIONS HANDLE JOINING/PAYING AND WITHDRAWING
	function restoreEscrow($user_id, $escrowAmt){
		// also update the user's virtual balance
		$this->db->where("id = ?", $user_id);
		$user = $this->db->select('users')[0];

		//$contrCents = $escrowAmt * 100;
		$contrCents = $escrowAmt; // in cents

		$_SESSION['user']['virtual_balance'] = $_SESSION['user']['virtual_balance'] + $contrCents;
		
		$this->db->query("UPDATE users SET virtual_balance = " . (((int) $user['virtual_balance']) + $contrCents) . " WHERE id = " . $user['id']);
	}
	
	function adjustTotals($pledgeAmt,$pid){
		// also update projects.contributions_count
		$this->db->where("id = ?", $pid);
		$project = $this->db->select('projects')[0];

		//$this->db->where("id = ?", $data['user_id']);
		//$user  = $this->db->select('users')[0];

		$this->db->query("UPDATE projects SET chip_ins = " . (((int) $project['chip_ins']) - 1) . ", crowdfund = " . (((int) $project['crowdfund']) - $pledgeAmt) . " WHERE id = " . $pid);
	}
	
	function adjustAlreadyPaid($pid,$amount){
		$this->db->where("id = ?", $pid);
		$project = $this->db->select('projects')[0];	
		
		$this->db->query("UPDATE projects SET already_paid = " . (((int) $project['already_paid']) - $amount) . " WHERE id = " . $pid);
	}
	
	function duplicate($project){
//		TEST THIS		
//		return $project['title'];
//		exit;
		
		$duplicate = $project;
		$base_id   = $project['id'];

		unset($duplicate['id']);
		unset($duplicate['timestamp_posted']);
		unset($duplicate['timestamp_end']);

		$duplicate['project_type_id'] = $duplicate['project_type_id'];
		$duplicate['title']   		= $duplicate['title'] . " Copy";
		$duplicate['description']   = $duplicate['description'];
		if (empty($duplicate['location'])) {
			$duplicate['location'] = "VoiceTrivia.com";
		} else {
			$duplicate['location']    	= $duplicate['location'];	
		}
		$duplicate['location_lat']  = $duplicate['location_lat'];
		$duplicate['location_lng']  = $duplicate['location_lng'];
		$duplicate['user_id'] 		= $_SESSION['user_id'];
		$duplicate['reviews_goal'] 		= $_SESSION['reviews_goal'];
		$duplicate['reviews_submitted'] = $_SESSION['reviews_submitted'];
		$duplicate['reviews_unlocked'] 	= $_SESSION['reviews_unlocked'];
		$duplicate['category_id']   = $duplicate['category_id'];
		$duplicate['main_img']    	= $duplicate['main_img'];
		$duplicate['is_featured']   = $duplicate['is_featured'];
		$duplicate['views']   		= 0;
		$duplicate['host']    		= $duplicate['host'];
		$duplicate['paypal_email']   = $duplicate['paypal_email'];
		$duplicate['tamount']   	= $duplicate['tamount'];
		$duplicate['status']   		= 'created';
		$duplicate['budget']     	= $duplicate['budget'];
		$duplicate['terms']   		= $duplicate['terms'];
		$duplicate['is_private']   		= $duplicate['is_private'];
		$duplicate['already_paid']  = $duplicate['already_paid'];
		$duplicate['specific_fee']  = $duplicate['specific_fee'];
		$duplicate['redeem_type']   = 'SINGLE USE COUPON';
		$duplicate['redeem_max']    = 1;
		$duplicate['redeem_max_global']   = 1;
		$duplicate['is_active']   	= $duplicate['is_active'];
		$duplicate['original_main_img'] = $duplicate['original_main_img'];
		$duplicate['price']   		= $duplicate['price'];
		$duplicate['date_to']   	= $duplicate['date_to'];
		$duplicate['date_from']   	= $duplicate['date_from'];		
		$duplicate['menu']   		= '';
		$duplicate['chef_user_id']  = 1;
		$duplicate['facilitator_user_id']  = 1;
		$duplicate['location2']    	= $duplicate['location'];
		$duplicate['location_lat2']  = $duplicate['location_lat'];
		$duplicate['location_lng2']  = $duplicate['location_lng'];
		$duplicate['type_id']   	= $duplicate['type_id'];
		$duplicate['tags']   		= $duplicate['tags'];
		$duplicate['pm']   			= $duplicate['pm'];
		$duplicate['pm_notes']   	= $duplicate['pm_notes'];
		$duplicate['qat']   		= $duplicate['qat'];
		$duplicate['qat_notes']   	= $duplicate['qat_notes'];	
		$duplicate['raised']   		= $duplicate['raised'];
		$duplicate['email']   		= $duplicate['email'];
		$duplicate['phone']   		= $duplicate['phone'];
		$duplicate['quickmatch']   	= $duplicate['quickmatch'];
		$duplicate['locspec']   	= $duplicate['locspec'];
		$duplicate['collab']   		= $duplicate['collab'];
		$duplicate['fmeligible']   	= $duplicate['fmeligible'];
		$duplicate['roi']   		= $duplicate['roi'];
		$duplicate['opportunity']   = $duplicate['opportunity'];
		$duplicate['chip_ins']   	= $duplicate['chip_ins'];
		$duplicate['last24hrs']   	= $duplicate['last24hrs'];
		$duplicate['crowdfund']   	= $duplicate['crowdfund'];
		$duplicate['budgetcf']  	= $duplicate['budgetcf'];
		$duplicate['entries']  		= $duplicate['entries'];
		$duplicate['allowed']  		= $duplicate['allowed'];
		$duplicate['multi']  		= $duplicate['multi'];

//		echo "<pre>";
//		print_r($duplicate);
//		exit;
		//$duplicate['slug']    		= $duplicate['slug'] . "-copy";
		//$duplicate['subtitle']    = $duplicate['subtitle'];
		$this->db->insert("projects", $duplicate);

		$duplicate['id'] = $this->db->insert_id();

		return $duplicate['id'];
	} 
	
	function getMyListings($user_id){
		//$this->db->order_by("chipins DESC");
		//$this->db->where('project_type_id=?', 2);
		//$this->db->where('is_active=?', 1);
		$this->db->where('user_id=?', $user_id);
		$projects = $this->db->select('projects');
		
		foreach ($projects as $index => $row) {
			$this->db->where('id = ?', $row['user_id']);
			$projects[$index]['user'] = $this->db->select('users')[0];

			$projects[$index]['days_to_end'] = round((strtotime($row['timestamp_end']) - time()) / 86400);

			$this->db->where('project_id=?', $row['id']);
			$projects[$index]['avg_rating'] = round($this->db->select('reviews', 'AVG(rating) AS r')[0]['r']);

			//$this->db->where('object_id=?', $row['id']);
			//$projects[$index]['favs'] = $this->db->select('user_favorites', "COUNT(*) AS amount")[0]['amount'];

			$this->db->where('item_id=?', $row['id']);
			$projects[$index]['backed_amount'] = $this->db->select('backing_history', "SUM(amount) AS amount")[0]['amount'];
			$this->db->where('item_id=?', $row['id']);
			$projects[$index]['backers'] = $this->db->select('backing_history', "COUNT(*) AS amount")[0]['amount'];

			if (!$projects[$index]['main_img']) {
				$this->db->where('project_id=?', $row['id']);
				$this->db->where('type=?', 'image');
				$projects[$index]['images'] = $this->db->select('uploads');
				$projects[$index]['main_img'] = $projects[$index]['images'][0]['file'];
			}

			$projects[$index]['proposals'] = $this->getProposals($row['id'],$user_id);
		}

		return $projects;
	}
	
	function incrementETotal($pid, $userid){
		$this->db->where("id = ?", $pid);
		$project = $this->db->select('projects')[0];

		$this->db->query("UPDATE projects SET etotal = " . (((int) $project['etotal']) +1) . " WHERE id = " . $pid);
		
		// NOW UPDATE THE USER'S CREDIT BALANCE
		$this->db->where("id = ?", $userid);
		$user = $this->db->select('users')[0];

		$_SESSION['user']['credits'] = $_SESSION['user']['credits'] -1;

		$this->db->query("UPDATE users SET credits = " . (((int) $user['credits']) - 1) . " WHERE id = " . $user['id']);
	}

}