<?php
// PRETTY SURE THIS IS THE MAIN MODEL FOR ALL CURRENT PROJECTS
class userModel
	extends baseModel
{
	const FAVTYPE_OBJECT  = 1;
	const FAVTYPE_PROJECT = 2; // DEVSHARES - IT SHOULD BE THIS ONE, I THINK
	const FAVTYPE_GROUP   = 3;
	const FAVTYPE_USER    = 4;
	const FAVTYPE_PRODUCT = 5;
	const FAVTYPE_LISTING = 6; // DEVSHARES MAYBE?
	const FAVTYPE_EVENT   = 7;

	public $image_folder = "/static/images/users/agency/";

	static public $fields = [
		'rank','name', 'is_admin', 'email', 'virtual_balance','location', 'location_lat','location_lng','location_last_lat','location_last_lng','balance','sold','refqty',
		'biography', 'website', 'phone', 'user_slug','paypal_email','instagram_username', 'linkedin_account',
		'height', 'weight', 'eye_color', 'willing_to_do', 'is_activated', 'specific_fee', 'account_type',
		'category_id', 'type_id', 'contact_name', 'contact_email', 'contact_phone', 'contact_best_time', 'mailing_address','mailing_address2',
		'x_exp_date','x_bank_acct_num' ,'x_bank_acct_type' ,'x_bank_aba_code' ,'x_bank_name' ,'x_first_name' ,
		'x_last_name' ,'x_company' ,'x_adress' ,'x_city' ,'x_state' ,'x_zip' ,'x_phone' ,'x_fax' ,'x_email','creditcard',
		'max_daily_alerts', 'image', 'user_push_id','first_name','last_name','bids','credits','temperaments','averating','batch','pos','win'
	];
	/**
	function assignCard($user_id) {
    	// get card
		$card = $this->db->where('assigned=0')
			->limit(1)
			->select_one('cards');
			 
		if ($card) {
			// update users table
			$this->db->where('id=?', $user_id)
				->limit(1)
				->update('users', [
					'cardnum' => $card['cardnumber']
				]);
				
			// update cards table
			$this->db->where('id=?', $card['id'])
				->limit(1)
				->update('cards', [
					'assigned' => '1'
				]);
		}
	}
     * 
     */

	function getUser($cond) {
		if (is_numeric($cond)) {
			$cond = ['id' => $cond];
		}

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

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

		$user = $this->db->select_one('users');

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

		if (empty($user['id']))
			return $user;

		// REVIEWS
		//$this->db->where('user_id=?', $user['id']);
		//$user['avg_rating_given'] = round($this->db->where('rating > 0', null)->select('reviews', 'AVG(rating) AS r')[0]['r'], 1);

		//$this->db->where('user_id=?', $user['id']);
		//$user['reviews_count'] = $this->db->select('reviews', 'COUNT(*) as c')[0]['c'];

		//$this->db->where('projects.user_id=?', $user['id']);
		//$this->db->join('projects', 'projects.id=reviews.id');
		//$user['avg_rating_received'] = round($this->db->where('rating > 0', null)->select('reviews', 'AVG(rating) AS r')[0]['r'], 1);

		// PROPOSALS
		//$this->db->where('projects.user_id=?', $user['id']);
		//$this->db->join('projects', 'projects.id=proposals.project_id');
		//$user['proposals_avg_rating_given'] = round($this->db->where('rating > 0', null)->select('proposals', 'AVG(rating) AS r')[0]['r'], 1);

		//$this->db->where('user_id=?', $user['id']);
		//$user['proposals_count'] = $this->db->select('proposals', 'COUNT(*) as c')[0]['c'];

		//$this->db->where('user_id=?', $user['id']);
		//$user['proposals_avg_rating_received'] = round($this->db->where('rating > 0', null)->select('proposals', 'AVG(rating) AS r')[0]['r'], 1);

		// groups
		//$this->db->where('user_id = ?', $user['id']);
		//$usergroups = $this->db->select('users_groups');
		//$groups     = [];
		//foreach ($usergroups as $entry)
		 //   $groups[$entry['group_id']] = $this->db->where('id = ?', $entry['group_id'])
		 //                            			   ->select('groups');
        //$user['groups'] = $groups;

        // favorites
        //$this->db->where("user_id = ?", $user['id']);
        //$ufavs     = $this->db->select("user_favorites");
        //$user['favorites'] = $this->getFavorites($user['id']);

        $location_fields = [
        	"concat(users.location_lat, ',', users.location_lng) as coordinates",
        	"concat(users.location_last_lat, ',', users.location_last_lng) as last_coordinates",
        	"users.location_lat as location_lat",
        	"users.location_lng as location_lng",
        	"users.location_last_lat as location_last_lat",
        	"users.location_last_lng as location_last_lng",
        ];
        $user['user_location'] = $this->db->where("id = ?", $user['id'])
	         							  ->select_one("users", $location_fields);
	    
	    $this->db->where('user_id=?', $user['id']);
		$this->db->where('type=?', 'image');
		$user['images'] = $this->db->select('uploads');

//	    $user_interests = $this->db->where("user_id = ?", $user['id'])
//	    							  ->join("interest", "interest.id = ui.interest_id")
//	    							  ->select("user_interests ui", "interest.tag");
//	    $interests      = [];
//	    foreach ($user_interests as $interest)
//	    	$interests[] = $interest['tag'];
//	    $user['interests'] = implode(", ", $interests);

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

		return $user;
	}
	
	function getPoster($user_id) {
		if (is_numeric($cond)) {
			exit;
		}

		$this->db->where('id=?', $user_id);
		$user = $this->db->select_one('users',['user_slug','name','image']);

		return $user;
	}	
	
	function getRecentMembers() {
		$this->db->limit = 20;
		$this->db->order_by('id DESC');
		$recent_members = $this->db->select('users',['user_slug','name','image','first_name','last_name']);

		return $recent_members;
	}	
	
	function getRecentMembers1() {
		$this->db->limit = 5;
		$this->db->order_by('rand()');
		$this->db->where('id BETWEEN 1 AND 188');
		$recent_members1 = $this->db->select('users',['user_slug','name','image','first_name','last_name','occupation_title','occupation_at','temperaments']);

		return $recent_members1;
	}	
	
	function getRecentMembers2() {
		$this->db->limit = 5;
		$this->db->order_by('rand()');
		$this->db->where('id BETWEEN 189 AND 308');
		$recent_members2 = $this->db->select('users',['user_slug','name','image','first_name','last_name','occupation_title','occupation_at','temperaments']);

		return $recent_members2;
	}	
	
	function getRecentMembers3() {
		$this->db->limit = 5;
		$this->db->order_by('rand()');
		$this->db->where('id BETWEEN 309 AND 322');
		$recent_members3 = $this->db->select('users',['user_slug','name','image','first_name','last_name','occupation_title','occupation_at','temperaments']);

		return $recent_members3;
	}	
	
	function getRecentMembers4() {
		$this->db->limit = 5;
		$this->db->order_by('rand()');
		$this->db->where('id BETWEEN 323 AND 1000');
		$recent_members4 = $this->db->select('users',['user_slug','name','image','first_name','last_name','occupation_title','occupation_at','temperaments']);

		return $recent_members4;
	}	

	function getLeaderboard() {
		$this->db->where('credits.type=?', 'earned');
		$this->db->order_by('earned_amount DESC');
		$this->db->group_by('user_id');
		$this->db->join('credits', 'credits.user_id = users.id');

		$users = $this->db->select("users", ['*', 'SUM(credits.amount) AS earned_amount']);

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

		return $users;
	}

	function getList($cond = []) {

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

		if (isset($cond['account_type']) && !is_array($cond['account_type']))
			$this->db->where("account_type = ?", $cond['account_type']);
		elseif (isset($cond['account_type']) && !is_array($cond['account_type']))
			$this->db->where("account_type IN ('" . implode("', '", $cond['account_type']) . "')");

		// Checks for a Referrer Promo Code	
		if (!empty($cond['ref']))
			$this->db->where("ref = ?", $cond['ref']);				
			
		if (isset($cond['search'])) {
			$cond['search'] = strtolower($cond['search']);
			$this->db->where("(
				lower(name) like '%{$cond['search']}%'
				OR lower(email) like '%{$cond['search']}%'
				OR lower(phone) like '%{$cond['search']}%'
				OR lower(biography) like '%{$cond['search']}%')");
		}

		if (isset($cond['justIds'])) {
			$users = $this->db->select('users', ['id', 'name']);
			return $users;
		} else {
			$users = $this->db->select('users');
		}
		
		foreach ($users as $index => $u)
			$users[$index] = $this->getUser($u['id']);

		return $users;
	}

	function getRandomThumbs() {
		$this->db->limit = 20;
		$this->db->order_by("RAND()");
		$thumbs = $this->db->where('image != ?', '')
			->where('image != ?', 'default-avatar.jpg')
			->select('users', 'user_slug, image, name');

		for ($x = 0; $x < 20; $x++) {
			if (!isset($thumbs[$x])) {
				$thumbs[$x] = ['image' => 'default-avatar.jpg'];
			}
		}

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

		return $thumbs;
	}

	function followUser($args) {
		$this->db->insert('users_followed', [
			'user_id_followed' => $args['followed'],
			'user_id_follower' => $args['follower'],
		]);
	}

	function unfollowUser($args) {
		$this->db->where('user_id_followed=?', $args['followed'])
			->where('user_id_follower=?', $args['follower'])
			->delete('users_followed');
	}

	function getFollowers($args) {
		if (isset($args['followed']) && is_numeric($args['followed'])) {
			$this->db->where('user_id_followed=?', $args['followed']);
		}
		if (isset($args['follower']) && is_numeric($args['follower'])) {
			$this->db->where('user_id_follower=?', $args['follower']);
		}
		$results = $this->db->select('users_followed');
		return $results;
	}

	function isFollowed($args) {
		$this->db->where('user_id_followed=?', $args['followed'])
			->where('user_id_follower=?', $args['follower'])
			->select('users_followed');

		return $this->db->affected_rows();
	}
	function updateUserLastLocation($user_id, $lat, $lng )
	{
		$currentUserInfo = $this->db->where('id=?', $user_id)->select_one('users');

		$this->db->where('id=?', $user_id)->update('users', [
			'location_last_lat' => $lat,
			'location_last_lng' => $lng,
			'last_coordinates'  => $lat . "," . $lng,
			'date_last_coordinates' => (new DateTime("now", new DateTimeZone("CST")))->format("Y-m-d H:i:s")
		]);

		// make sure to match geolocation related targeted deals !
		$campaignModel = new campaignModel();
		$campaignModel->matchTargetedDeals(['user_id' => $user_id]);
	}
	
	function updateUser($user_id, $data, $files = []) {
//		if ($data['phone']) {
//			$data['phone'] = format_phone(preparePhone($data['phone']));
//			if (strlen($data['phone']) != 12) {
//				$data['phone'] = '';
//			}
//		}

		$currentUserInfo = $this->db->where('id=?', $user_id)->select_one('users');

		if ($data['phone'] && $currentUserInfo['phone'] != $data['phone']) {
			require "3rdparty/twilio-php-master/Services/Twilio.php";

			// set your AccountSid and AuthToken from www.twilio.com/user/account
			$AccountSid = "ACc33ee9aa71e9a841111c0f6ef976af61";
			$AuthToken = "774b5173cc5c1ba2b61ee20769888fa1";

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

			$message = $client->account->messages->create(array(
			    "From" => "+13128789582",
			    "To" => $data['phone'],
			    "Body" => "Welcome to VoiceTrivia",
			));
		}

		if ($files && $files['image']) {
			$old_filename = $files['image']['name'];
			$ext = substr($old_filename, strrpos($old_filename, '.')+1);
			$new_filename = $user_id . "-" . time() . ".$ext";

			if (in_array($ext, ['png', 'jpg', 'jpeg', 'gif'])) {
				$user = $this->getUser($user_id);
				@unlink($user['image']);

				move_uploaded_file($files['image']['tmp_name'], 'static/images/users/' . $new_filename);

				$this->db->where('id=?', $user_id);
				$this->db->update('users', ['image' => $new_filename]);
				$_SESSION['user']['image'] = $new_filename;
			}
		}

		if (!empty($data['files'])) {
			require_once 'models/uploadsModel.php';
			$uploadsModel = new uploadsModel();
			foreach ($data['files'] as $file) {
				$file = $uploadsModel->select($file);
				if (empty($file))
					continue;

				$uploadsModel->update($file['id'], ['user_id' => $user_id]);
				if (empty($currentUserInfo['image']) || $currentUserInfo['image'] == 'default-avatar.jpg') {
					$data['image'] 				= $file['file'];
					$currentUserInfo['image']   = $file['file'];
				}
			}
		}

		$data_to_update = $data;
		foreach ($data_to_update as $index => $value) {
			if (!in_array($index, self::$fields)) {
				unset($data_to_update[$index]);
			} else {
				$data_to_update[$index] = trim(htmlentities($value));
			}
		}

		if (isset($data['password']) && trim($data['password'] != '')) {
			$authModel = new authModel();
			$data_to_update['password'] = $authModel->encodePwd($data['password']);
		}

		// validate and modify if needed bfore saving new slug.
		if (!empty($data['user_slug']) && $data['user_slug'] != $currentUserInfo['user_slug'])
			$data_to_update['user_slug'] = $this->getAvailableSlug($data['user_slug']);

		$this->db->where('id=?', $user_id);
		$this->db->update('users', $data_to_update);
	}

	function getAvailableSlug($slug)
	{
		$slug = slug($slug);

		$this->db->where('user_slug=?', $slug);
		$this->db->select('users');

		$c = 1;
		while ($this->db->affected_rows() || $slug == 'edit') {
			$c++;
			$slug = slug($slug) . $c;
			$this->db->where('user_slug=?', $slug);
			$this->db->select('users');
		}

		return $slug;
	}

	function getServices($user_id) {
		$this->db->where('user_id=?', $user_id);
		$this->db->join('services', 'services.id=user_to_service.service_id');
		$services = $this->db->select('user_to_service');
		return $services;
	}

	function makeThumbnails()
	{
		$users = $this->db->select('users');
		foreach ($users as $value) {
			if (empty($value['image']) || filter_var($value['image'], FILTER_VALIDATE_URL)) {
				continue;
			}

			$file = ltrim($this->image_folder . $value['image'], '/');
			if (!file_exists($file)) {
				continue;
			}

			resizeImg($file, 200, true);
		}

		return true;
	}

	function insert($data)
	{
    	if (! isset($data['email']) && ! isset($data['phone']))
        	// one of email or phone_number is mandatory !
    	    return false;

        $this->db->insert("users", $data);
        return $this->db->insert_id();
	}

	function getFavoriteObject($row)
	{
        //$objectModel  = new objectModel();
        $projectModel = new projectModel();
        //$groupModel   = new groupModel();
        $userModel 	  = new userModel();
		//$productModel = new productModel();
		//$listingsModel = new listingsModel();

		switch ($row['type_id']) {
		default:
		//case self::FAVTYPE_OBJECT:
		//	return $objectModel->get($row['object_id']);
		case self::FAVTYPE_PROJECT:
			return $projectModel->get($row['object_id']);
		//case self::FAVTYPE_GROUP:
		//	return $groupModel->get($row['object_id']);
		case self::FAVTYPE_USER:
			return $userModel->getUser($row['object_id']);
		//case self::FAVTYPE_PRODUCT:
		//	return $productModel->get($row['object_id']);			
		//case self::FAVTYPE_LISTING:
		//	return $listingsModel->get($row['object_id']);	
		case self::FAVTYPE_EVENT:
			return $projectModel->get($row['object_id']);		
    	}		
	}

	function getFavorites($user_id, $type_id = 0) {
        $favorites = [];

        if ($type_id > 0)
        	$this->db->where("type_id = ?", $type_id);

		$this->db->where("user_id = ?", $user_id);
        $ufavs     = $this->db->select("user_favorites");
        foreach ($ufavs as $entry) {
        	$object = $this->getFavoriteObject($entry);
        	$object['favorite_type'] = $entry['type_id'];

            $favorites[$entry['object_id']] = $object;
        }

		return $favorites;
	}

	function toggleFavorite($user_id, $object_id, $type_id = 1)
	{
		$exists = $this->db->where("user_id = ?", $user_id)
						   ->where("object_id = ?", $object_id)
						   ->where("type_id = ?", $type_id)
						   ->select_one("user_favorites");
		if (empty($exists))
			// toggle action is ADD
			$this->db->insert("user_favorites", array(
				"user_id" 	=> $user_id,
				"object_id" => $object_id,
				"type_id" 	=> $type_id));
		else
			// toggle action is REMOVE
			$this->db->where("user_id = ?", $user_id)
					 ->where("object_id = ?", $object_id)
					 ->where("type_id = ?", $type_id)
					 ->delete("user_favorites");

		return empty($exists);
	}

	function updateFavorites($user_id, array $favorites)
	{
		$favs_before = $this->db->where("user_id = ?", $user_id)
								->select("user_favorites", "object_id");
		$old_favs_id = [];
		$new_favs_id = [];

		// generate lists
		foreach ($favs_before as $fav)
			$old_favs_id[] = $fav['object_id'];

		foreach ($favorites as $favs) {
			$object_id = $object;
			if (is_array($object))
				$object_id = $object['id'];

			$new_favs_id[] = $object_id;

			if (in_array($object_id, $old_favs_id))
				// already in db
				continue;

			// insert new favorites
			$this->db->insert("user_favorites", array(
				"user_id" 	=> $user_id,
				"object_id" => $object_id));
		}

		// check for removed favorites
		$removed_favs_id = array_diff($old_favs_id, $new_favs_id);
		if (empty($removed_favs_id))
			return $new_favs_id;

		// need to delete removed favorites from db
		foreach ($removed_favs_id as $fav)
			$this->db->where("user_id = ?", $user_id)
					 ->where("object_id = ?", $fav)
					 ->delete("user_favorites");

		return $new_favs_id;
	}

	function getProposals($user_id, $hired = null) {
		if (!is_numeric($user_id)) {
			return -1;
		}

		$this->db->where('user_id=?', $user_id);

		if ($hired)
			// get only hired proposals of user
			$this->db->where("status = 1", null);

		$this->db->order_by("`timestamp` DESC");
		$r = $this->db->select('proposals', ['*', 'proposals.id AS proposal_id']);

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

			$r[$index]['project']   = $projectModel->get($review['project_id']);
			$r[$index]['candidate'] = $this->getUser($review['user_id']);
		}

		return $r;
	}

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

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

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

		$this->db->order_by("ord ASC, slider_group ASC");
		$acts = $this->db->select("featured_accounts");
		return $acts;
	}

	function updateFeaturedAccount($id, $data) {

		$this->db->where("id = ?", $id);
		$cur_images = $this->db->select_one("featured_accounts", ['image', 'image_mobile']);

		if (! empty($data['files'])) {

			$this->db->where("id = ?", (int) $data['files'][0]);
			$image_0 = $this->db->select_one("uploads", ["file"])['file'];

			if ($data['files'][0] && !empty($cur_images['image']) && empty($cur_images['image_mobile'])) {
				// already has image but no mobile.
				$this->db->where('id=?', $id);
				$this->db->update('featured_accounts', ['image_mobile' => $image_0]);
			}
			elseif ($data['files'][0] && empty($cur_images['image'])) {
				// no image yet
				$this->db->where('id=?', $id);
				$this->db->update('featured_accounts', ['image' => $image_0]);
			}
			elseif ($data['files'][0] && $data['files'][1]) {
				$this->db->where("id = ?", (int) $data['files'][1]);
				$image_1 = $this->db->select_one("uploads", ["file"])['file'];

				$this->db->where('id=?', $id);
				$this->db->update('featured_accounts', [
					'image' => $image_0,
					'image_mobile' => $image_1]);
			}
		}

		if ($data['files'][1] && empty($cur_images['image_mobile'])) {
			// save mobile image
			$this->db->where("id = ?", (int) $data['files'][1]);
			$image_1 = $this->db->select_one("uploads", ["file"])['file'];

			$this->db->where('id=?', $id);
			$this->db->update('featured_accounts', ['image_mobile' => $image_1]);
		}

		$update_data = [];
		$update_data['title']  	   = !empty($data['title']) ? $data['title'] : "";
		$update_data['content']    = !empty($data['content']) ? $data['content'] : "";
		$update_data['embed_html'] = !empty($data['embed_html']) ? $data['embed_html'] : "";
		$update_data['video'] = !empty($data['video']) ? $data['video'] : "";	
		$update_data['notes'] = !empty($data['notes']) ? $data['notes'] : "";
		$update_data['ord']  	   = !empty($data['ord']) ? $data['ord'] : "";
		$update_data['slider_group'] = !empty($data['slider_group']) ? $data['slider_group'] : "";
		$update_data['countdown_until'] = !empty($data['countdown_until']) ? $data['countdown_until'] : "";
		$update_data['enable_feature_1'] = !empty($data['enable_feature_1']) ? 1 : 0;
		$update_data['enable_feature_2'] = !empty($data['enable_feature_2']) ? 1 : 0;
		$update_data['enable_feature_3'] = !empty($data['enable_feature_3']) ? 1 : 0;
		$update_data['enable_feature_4'] = !empty($data['enable_feature_4']) ? 1 : 0;	
		$update_data['enable_feature_5'] = !empty($data['enable_feature_5']) ? 1 : 0;	
		if(!empty($data['overlay']) && $data['overlay'] == 100) {
			$update_data['overlay'] = 99;
		} else {
			$update_data['overlay'] = !empty($data['overlay']) ? $data['overlay'] : "";			
		}
		$update_data['btntitle']  	   = !empty($data['btntitle']) ? $data['btntitle'] : "";
		$update_data['btnurl']  	   = !empty($data['btnurl']) ? $data['btnurl'] : "";
		$update_data['titlecolor']  	   = !empty($data['titlecolor']) ? $data['titlecolor'] : "";

		if (!empty($update_data['countdown_until'])) {
			// need to reformat the date
			list ($m, $d, $yt) = explode("/", $update_data['countdown_until']);
			list ($y, $t)      = explode(" ", $yt);
			list ($h, $i) 	   = explode(":", $t);

			$update_data['countdown_until'] = "{$y}-{$m}-{$d} {$h}:{$i}:00";
		}

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

	function deleteFeaturedAccountImage($fid, $image)
	{
		$this->db->where("id = ?", $fid);
		$this->db->update("featured_accounts", [$image => ""]);
	}

	function insertFeaturedAccount($data) {
		$insert_data = [];
		if (!empty($data['title']))
			$insert_data['title'] = $data['title'];

		if (!empty($data['content']))
			$insert_data['content'] = $data['content'];

		if (!empty($data['embed_html']))
			$insert_data['embed_html'] = $data['embed_html'];

		if (!empty($data['video']))
			$insert_data['video'] = $data['video'];		
		
		if (!empty($data['notes']))
			$insert_data['notes'] = $data['notes'];		
		
		if (!empty($data['ord']))
			$insert_data['ord'] = $data['ord'];		
		
		if (!empty($data['slider_group']))
			$insert_data['slider_group'] = $data['slider_group'];

		if (!empty($data['countdown_until']))
			$insert_data['countdown_until'] = $data['countdown_until'];
		
		if (!empty($data['btntitle']))
			$insert_data['btntitle'] = $data['btntitle'];	

		if (!empty($data['btnurl']))
			$insert_data['btnurl'] = $data['btnurl'];	

		if (!empty($data['titlecolor']))
			$insert_data['titlecolor'] = $data['titlecolor'];			

		if (! empty($data['files'][0])) {
			// get filename
			$this->db->where("id = ?", (int) $data['files'][0]);
			$image = $this->db->select_one("uploads", ["file"])['file'];

			$insert_data['image'] = $image;
		}

		if (! empty($data['files'][1])) {
			// get filename
			$this->db->where("id = ?", (int) $data['files'][1]);
			$image = $this->db->select_one("uploads", ["file"])['file'];

			$insert_data['image_mobile'] = $image;
		}

		$this->db->insert('featured_accounts', $insert_data);
	}

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

	function deleteFeaturedAccount($id) {
		$this->db->where('id=?', $id);
		$this->db->delete('featured_accounts');
	}
    
    // UPDATE THE DEVICE ID FROM THE MOBILE API
    function updateDeviceID($user_id,$deviceID) {
        // get the user
        $user = $this->db->where('id=?', $user_id)
            ->limit(1)
            ->select_one('users');
             
        if ($user) {
            // update users table
            $this->db->where('id=?', $user_id)
                ->limit(1)
                ->update('users', [
                    'user_push_id' => $deviceID
                ]);
        }
    }    
    
	function getBalance($user_id){
		$this->db->where('id=?', $user_id);
		$user = $this->db->select('users')[0];

		if (!empty($user)) {
			return $user['virtual_balance'];
		}
	}
	
	function updateBalance($user_id, $amount){
		$updateStatus = $this->db->query("UPDATE users SET virtual_balance=virtual_balance-'$amount' 
		WHERE id='$user_id'");
		
		return $updateStatus;
	}
    
	// RESERVE APPWRAPR
//	function reserveAppWrapr($user_id)
//	{
//		//echo $user_id;
//		// get the user
//		$user = $this->db->where('id=?', $user_id)
//		->limit(1)
//		->select_one('users');
//
//		if ($user) {
//			if ($user['external_id']==1) {
//				echo 2;
//			} else {
//				// update users table
//				$this->db->where('id=?', $user_id)
//				->limit(1)
//				->update('users', [
//					'external_id' => 1
//				]);
//				echo 1;
//			}
//		}
//		//echo 1;
//	}
	
//	function getLeaderboard(){
//		//$players = $this->db->where('quiz = ?', 'McDonalds Voice Trivia') // was stars, now credits
//		//$players = $this->db->where('external_id = ?', 1) // was stars, now credits
//		//$users = $this->db->where('balance != ?', '') // was stars, now credits
//		//$players = $this->db->select('api_results', '*');
//		//$this->db->limit = 500;
//		
//		//$this->db->where("user_id = ?", $user_id);
//		//$quiz = "McDonalds Voice Trivia";
//		//$this->db->where("quiz = ?", $quiz);
//		$players = $this->db->select("api_results");
//		
//		//print_r($players);
//		return $players;
//	}
	// WAIT LIST
//	function getLeaderboardOLD()
//	{
//		$this->db->limit = 500;
//		$this->db->order_by("balance DESC"); // was stars, now credits
//		//$this->db->order_by("RAND()");
//		// external_id = 0 default and 1 means reserved
//		$users = $this->db->where('external_id = ?', 1) // was stars, now credits
//		//$users = $this->db->where('balance != ?', '') // was stars, now credits
//		->select('users', '*');
//
//		//$this->db->where('credits.type=?', 'earned');
//		//$this->db->order_by('earned_amount DESC');
//		//$this->db->group_by('user_id');
//		//$this->db->join('credits', 'credits.user_id = users.id');
//
//		//$users = $this->db->select("users", ['*', 'SUM(credits.amount) AS earned_amount']);
//		//$users = $this->db->select("users", ['*', 'stars']);
//
//		foreach ($users as $index => $u) {
//			if ($u['image'] != '' && !strstr($u['image'], '//')) {
//				//$users[$index]['image'] = $this->image_folder . $u['image'];
//				$users[$index]['image'] = "/static/images/users/agency/" . $u['image'];
//			} else {
//				$users[$index]['image'] = 'https://voicetrivia.com/static/images/users/agency/251_profile.jpg';
//			}
//		}
//
//		return $users;
//	}
	// THIS CHOOSES THE WINNERS
//	function getWinners()
//	{
//		$this->db->limit = 5;
//		$this->db->order_by("RAND()");
//		$this->db->where('name !=?', '');
//		$this->db->where('image !=?', '');
//		$winners = $this->db->select('users');
//
//		$last_drawing_id = mysql_fetch_row(mysql_query("SELECT max(drawing_id) AS drawing_id FROM users_winners ORDER BY id DESC LIMIT 1"));
//
//		if (empty($last_drawing_id)) {
//			$drawing_id = 1;
//		} else {
//			$drawing_id = $last_drawing_id[0] + 1;
//		}
//
//		$i = 0;
//		foreach ($winners as $index => $u) {
//			$i++;
//			if ($u['image'] != '' && !strstr($u['image'], '//')) {
//				$winners[$index]['image'] = $this->image_folder . $u['image'];
//			} else {
//				$winners[$index]['image'] = 'https://voicetrivia.com/static/images/users/agency/default-avatar.jpg';
//			}
//			//user_id, drawing_id
//			$query = mysql_query("INSERT INTO users_winners(`user_id`,`rank`,`drawing_id`)VALUES('" . $u['id'] . "','" . $i . "','" . $drawing_id . "')");
//		}
//
//		//return $winners;
//	}

//	function getZinners()
//	{
//		$this->db->limit = 55;
//		$this->db->order_by("drawing_id DESC, rank ASC");
//		$this->db->join('users_winners', 'users_winners.user_id = users.id');
//		$zinners = $this->db->select('users');
//
//		foreach ($zinners as $index => $u) {
//			if ($u['image'] != '' && !strstr($u['image'], '//')) {
//				//$zinners[$index]['image'] = $this->image_folder . $u['image'];
//				$zinners[$index]['image'] = "/static/images/users/agency/" . $u['image'];
//			} else {
//				$zinners[$index]['image'] = 'https://voicetrivia.com/static/images/users/agency/default-avatar.jpg';
//			}
//		}
//
//		return $zinners;
//	}       
     
}