<?php
// THIS ONE CONTROLS THE MEMBERS PROFILES
class squareusersModel extends baseModel {

    public $tableName = 'users';
    
	const FAVTYPE_OBJECT  = 1;
	const FAVTYPE_PROJECT = 2; // FLIPMOBS
	const FAVTYPE_GROUP   = 3; // BUYING/SELLING
	const FAVTYPE_USER    = 4;
	const FAVTYPE_PRODUCT = 5;
	const FAVTYPE_LISTING = 6;
	const FAVTYPE_EVENT   = 7;  

	public $image_folder = "/static/images/users/agency/";
	
	static public $fields = [
		'rank','name','is_admin','email','location','location_lat','location_lng','location_last_lat',
		'location_last_lng','biography','website','phone','user_slug','paypal_email','instagram_username', 
		'linkedin_account','height', 'weight', 'eye_color', 'willing_to_do','is_approved','is_activated','specific_fee',
		'account_type','category_id','type_id', 'contact_name', 'contact_email','contact_phone', 
		'contact_best_time', 'mailing_address','mailing_address2','directory',
		'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','reg_date','square_id','birthday','virtual_balance',
		'balance','sold','refqty',
		'is_verified_phone','verified_date','address','address2','city','state','zip','deliv_type','special',
		'contactless','make','model','color','usertype','permissions','is_subscribe','is_text','is_push',
		'insurance','attach1','attach2','attach3','bus_type','is_sub','social_link','www','bids','credits',
		'temperaments','shares','location2','location2_lat','location2_lng','m1','dist1','m2','dist2',
		'occupation_at','occupation_title','interests','given_name','family_name','profilebg','averating','acct_type',
		'show_addy','list','creator','crenewal','super','srenewal','tix','mult','activec','actives','memType'
	];	
	
	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 get($id = 0) {
        if (!is_numeric($id)) {
            return -1;
        }
        $this->db->where('id = ?', $id);
        $square_user = $this->db->select('users')[0];

        return $square_user;
    }
    
	function getListOLD($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 getList($cond = []) {
    	
		//print_r($cond);
    	
		if (!empty($cond['client_id']))
			$this->db->where("org_id = ?", $cond['client_id']);
    	
		if (isset($cond["is_admin"]) && is_numeric($cond["is_admin"]) && $cond["is_admin"]==1) {
			$this->db->where("is_admin = ?", $cond["is_admin"]);
		}	
				
		if (isset($cond["permissions"]) && is_numeric($cond["permissions"]) && $cond["permissions"] > 0) {
			$this->db->where("permissions = ?", $cond["permissions"]);
		}		

		if (!empty($cond['usertype']))
			$this->db->where("usertype = ?", $cond['usertype']);
		
		if (!empty($cond['super']))
			$this->db->where("super = ?", $cond['super']);		
		
		if (!empty($cond['memType']))
			$this->db->where("memType = ?", $cond['memType']);
		// We may want to do an is_team just to be safe, so employees don't get access to Admin features
//		if(isset($cond["is_super"]) && is_numeric($cond["is_super"]) && $cond["is_super"]==2){
//			$this->db->where("is_super = ?", 1);
//		}

			$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(given_name) like '%{$cond['search']}%'
				OR lower(family_name) like '%{$cond['search']}%'	
				OR lower(list_group) like '%{$cond['search']}%'		
				)
				");			

		$users = $this->db->select('users');	
		return $users;
    }
    
	function currentMembersinGroup($group_id){
		$existing_users = $this->db->where("group_id = ?", $group_id)
		->order_by('user_id ASC')
		->select("groups_invite");
		
//		return $existing_users;
//		exit;

//				print_r($existing_users);
//				exit;

		$current_member_ids = [];

		foreach ($existing_users as $user) {
			$current_member_ids[] = $user['user_id'];
		}

		return $current_member_ids;
	}    
    
	function getMembersinList($cond = []){
		
		//print_r($cond);
		//$this->db->where("id = ?", $_SESSION['user']['id']);

		// We need to get the users from the groups_invite table and show them here too
		//$this->db->where("group_id = ?", $cond["group_id"]);
		//$members = $this->db->select('groups_invite');
//		print_r($members);
//		exit;
		
		if (!empty($cond['group_id']))
			$membs = $this->currentMembersinGroup($cond['group_id']);
		
			$memList = implode(', ', $membs);
			//$this->db->where("id IN(4,187)");

		// client_id is the logged in user's session id
		if (!empty($cond['client_id']))
			$this->db->where("(
					org_id = {$cond['client_id']}
					OR id = {$_SESSION['user']['id']}
					OR id IN($memList)
				)
			");
			//$this->db->where("org_id = ?", $cond['client_id']);

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

		if (isset($cond["permissions"]) && is_numeric($cond["permissions"]) && $cond["permissions"] > 0) {
			$this->db->where("permissions = ?", $cond["permissions"]);
		}

		if (!empty($cond['usertype']))
			$this->db->where("usertype = ?", $cond['usertype']);
		// We may want to do an is_team just to be safe, so employees don't get access to Admin features
		//		if(isset($cond["is_super"]) && is_numeric($cond["is_super"]) && $cond["is_super"]==2){
		//			$this->db->where("is_super = ?", 1);
		//		}

		//
		$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(given_name) like '%{$cond['search']}%'
				OR lower(family_name) like '%{$cond['search']}%'
				OR lower(list_group) like '%{$cond['search']}%'
				)
				");

		$users = $this->db->select('users');
		return $users;		
	}

    function getSquareUser($id) {
    	
//        $this->db->where('id=?', $id);
//        return $this->db->select('users')[0];

        $this->db->where('id=?', $id);
        $user = $this->db->select('users')[0];  
        
//		$this->db->where('user_id=?', $user['id']);
//		$this->db->where('type=?', 'image');
//		$user['images'] = $this->db->select('uploads');
		
		return $user;     
    }
    
    function getSubscriber($id) {
        $this->db->where('ver_code=?', $id);
        return $this->db->select('users')[0];
    }
    
    function getUserContactDetails($id) {
        $this->db->where('id=?', $id);
        return $this->db->select('users',['id','email','phone','is_subscribe','is_text','is_push','user_push_id','name','ver_code','user_slug'])[0];
    }    
    function markHidden($id,$checked) {
        $this->db->where('id=?', $id);
        $this->db->update('users', ['is_excluded' => $checked]);
    }

    function updateSquareUser($user_id, $data, $files = []) {
    	
		$currentUserInfo = $this->db->where('id=?', $user_id)->select_one('users');
		
		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/agency/' . $new_filename);

				$this->db->where('id=?', $user_id);
				$this->db->update('users', ['image' => $new_filename]);
			}
		}				
		
		$data_to_update = $data;
        
		$this->db->where('id=?', $user_id);
		$this->db->update('users', $data_to_update);        
    }   
    
	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 = "c59c52fa68a0813bfedfb13cb0f05fae";
//
//			$client = new Services_Twilio($AccountSid, $AuthToken);
//
//			$message = $client->account->messages->create(array(
//			    "From" => "312-878-9582",
//			    "To" => $data['phone'],
//			    "Body" => "Welcome to the LuxBrande-Pre-Order Demo Shop!",
//			));
//		}

		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', 'webp'])) {
				$user = $this->getUser($user_id);
				@unlink($user['image']);

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

				$this->db->where('id=?', $user_id);
				$this->db->update('users', ['image' => $new_filename]);
			}
		}
		
		if ($files && $files['profilebg']) {
			$old_filename = $files['profilebg']['name'];
			$ext = substr($old_filename, strrpos($old_filename, '.')+1);
			$new_filename = $user_id . "-" . time() . ".$ext";

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

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

				$this->db->where('id=?', $user_id);
				$this->db->update('users', ['profilebg' => $new_filename]);
			}
		}
		
		if ($files && $files['insurance']) {
			$old_insurance_filename = $files['insurance']['name'];
			$insurance_ext = substr($old_insurance_filename, strrpos($old_insurance_filename, '.')+1);
			$new_ins_filename = $user_id . "-" . time() . ".$insurance_ext";

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

				move_uploaded_file($files['insurance']['tmp_name'], 'static/images/users/attachments/' . $new_ins_filename);

				$this->db->where('id=?', $user_id);
				$this->db->update('users', ['insurance' => $new_ins_filename]);
			}
		}	
		
		if ($files && $files['attach1']) {
			$old_filename1 = $files['attach1']['name'];
			$ext1 = substr($old_filename1, strrpos($old_filename1, '.')+1);
			$new_filename1 = $user_id . "-" . time() . ".$ext1";

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

				move_uploaded_file($files['attach1']['tmp_name'], 'static/images/users/attachments/' . $new_filename1);

				$this->db->where('id=?', $user_id);
				$this->db->update('users', ['attach1' => $new_filename1]);
			}
		}
		
		if ($files && $files['attach2']) {
			$old_filename2 = $files['attach2']['name'];
			$ext2 = substr($old_filename2, strrpos($old_filename2, '.')+1);
			$new_filename2 = $user_id . "-" . time() . ".$ext2";

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

				move_uploaded_file($files['attach2']['tmp_name'], 'static/images/users/attachments/' . $new_filename2);

				$this->db->where('id=?', $user_id);
				$this->db->update('users', ['attach2' => $new_filename2]);
			}
		}	
		
		if ($files && $files['attach3']) {
			$old_filename3 = $files['attach3']['name'];
			$ext3 = substr($old_filename3, strrpos($old_filename3, '.')+1);
			$new_filename3 = $user_id . "-" . time() . ".$ext3";

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

				move_uploaded_file($files['attach3']['tmp_name'], 'static/images/users/attachments/' . $new_filename3);

				$this->db->where('id=?', $user_id);
				$this->db->update('users', ['attach3' => $new_filename3]);
			}
		}					

		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['is_subscribe'] = !empty($data['is_subscribe']) ? 1 : 0;
		$data['is_text'] = !empty($data['is_text']) ? 1 : 0;
		$data['is_push'] = !empty($data['is_push']) ? 1 : 0;
		//$data['is_approved'] = !empty($data['is_approved']) ? 1 : 0;
		
		$data['directory'] = !empty($data['directory']) ? 1 : 0;
		$data['is_sub'] = !empty($data['is_sub']) ? 1 : 0;
		
		$data['m1'] = !empty($data['m1']) ? 1 : 0;
		$data['m2'] = !empty($data['m2']) ? 1 : 0;
		
		$data['show_addy'] = !empty($data['show_addy']) ? 1 : 0;
		
		$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));
			}
		}
		
//		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 updateCategory($id, $data) {
//      $this->db->where('id=?', $id);
//      $this->db->update('categories', $data);
//  }

//  function insertCategory($title) {
//      $this->db->insert('categories', ['title' => $title]);
//  }

    function insertSquareUser($data) {
        if (isset($_FILES['image']) && !$_FILES['image']['error']) {
            
            $file = $_FILES['image'];
             
            $imgname = strtolower(basename($_FILES["image"]["name"]));
            if ($ext == 'jpg' || $ext == 'png' || $ext = 'jpeg' || $ext = 'gif') {              
                $destination = "static/uploads/users/$imgname";
                move_uploaded_file($file['tmp_name'], $destination);
                $data['image'] = $destination;
            }
        }           
        $this->db->insert('users', $data);
    }
    
    function insertSquareUsercropped($id, $img) {
        
        $squarecat = $this->db->where("id = ?", $id)
                          ->select_one("users");    

        $squarecattitle = str_replace(' ','',strtolower($squarecat['name']));    
        $squarecatname  = substr($squarecattitle,0,10);
        // FOR MY NOTES substr($string,0,10).'...';
        
        //$data = $img;

        //list($type, $data) = explode(';', $data);
        //list(, $data)      = explode(',', $data);
        
        $image_parts = explode(";base64,", $img);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);       
        
        //$data = base64_decode($data);
        //$imageName = 'atest'.time().'.png';
        $imageName = $squarecatname.'_'.time().'.png';
        $imagePath = 'static/uploads/users/'.$imageName;

        file_put_contents($imagePath, $image_base64);   

		$siteroot = $_SERVER['SERVER_NAME'];
		$croppedimg = "https://".$siteroot."/static/uploads/users/".$imageName;

		// OLD CODE
        //$croppedimg = "https://preorder.sqdash.co/static/uploads/users/".$imageName;
            
        $this->db->where('id=?', $id);
        $this->db->update('users', ['image' => $croppedimg]);               
    }        
    
     public function generateImage($img){
        $folderPath = "images/";

        $image_parts = explode(";base64,", $img);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);
        $file = $folderPath . uniqid() . '.png';

        file_put_contents($file, $image_base64);
    }   
     
    // $base64 = "data:image/png;base64,gAAAQ8AAAC6CAMAAACHgTh+AA=";

    // if(preg_match("^data:image\/(?<extension>(?:png|gif|jpg|jpeg));base64,(?<image>.+)$", $base64, $matchings))

	function getFavorites($user_id, $type_id = 5) {
        $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 getFavoriteObject($row)
	{
        $objectModel  = new objectModel();
        $projectModel = new projectModel();
        $groupModel   = new groupModel();
        $userModel 	  = new userModel();
		$producttModel = new producttModel();
		$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 $producttModel->get($row['object_id']);			
		case self::FAVTYPE_LISTING:
			return $listingsModel->get($row['object_id']);			
    	}		
	}	

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

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

    function getItem($id) {
        $this->db->where('id=?', $id);
        return $this->db->select('users')[0];
    }
    
	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")
		]);
	}  
	
	function updateNeighborhood($user_id, $coords_str, $neighborhood_address){
		
		$currentUserInfo = $this->db->where('id=?', $user_id)->select_one('users');

		$this->db->where('id=?', $user_id)->update('users', [
			'neighborhood_address' => $neighborhood_address,
			'neighborhood_coordinates'  => $coords_str
		]);
	}  	  
	
	function TotalUsers(){
		$total = $this->db->query('
			SELECT
			COUNT(*)
			FROM
			users
			')->fetch_row()[0];

		return $total;
	}
	
	function TotalEmployees($client_id){
		$total = $this->db->query('
			SELECT
			COUNT(*)
			FROM
			users WHERE org_id="'.$client_id.'"
			')->fetch_row()[0];

		return $total;
	}	

	function paginateUsers($page_no,$limit){
		$start_from = ($page_no-1) * $limit;
		$this->db->limit("{$start_from} , {$limit}");
		$users=$this->db->select('users');

		return $users;
	}
	
	function paginateEmployees($page_no,$limit,$client_id){
		$start_from = ($page_no-1) * $limit;
		$this->db->limit("{$start_from} , {$limit}");
		$this->db->where('org_id=?', $client_id);
		$users=$this->db->select('users');

		return $users;
	}	
	
	/////////////////////////////////////////////////////////
	// FOLLOWERS FUNCTIONS START HERE
	/////////////////////////////////////////////////////////
		
	function followUser($args) {
		
		$exists = $this->db->where('user_id_followed=?', $args['followed'])
		->where('user_id_follower=?', $args['follower'])
		->select('users_followed');
		
		if (empty($exists)) {
			$this->db->insert('users_followed', [
				'user_id_followed' => $args['followed'],
				'user_id_follower' => $args['follower'],
			]);	
		} else {
			return 0;
		}
	}

	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 getFollowing($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) {
		$exists = $this->db->where('user_id_followed=?', $args['followed'])
			->where('user_id_follower=?', $args['follower'])
			->select('users_followed');

		//print_r($exists);
		if (!empty($exists)) {
			return 1;
		}
		//return $this->db->affected_rows();
	}	
	
	function getTotalFollowing($user_id){
		$totalfollowing = $this->db->query('
			SELECT
			COUNT(*)
			FROM users_followed 
			WHERE user_id_follower="'.$user_id.'"
			')->fetch_row()[0];

		return $totalfollowing;
	}
	
	function checkFollowUser($args) {
		$exists = $this->db->where('user_id_followed=?', $args['followed'])
		->where('user_id_follower=?', $args['follower'])
		->select('users_followed');
		
		if (empty($exists)) {
			return 1; // I do not follow
		} else {
			return 0; // I follow
		}
	}
	
	/////////////////////////////////////////////////////////
	// FRIENDS FUNCTIONS START HERE
	/////////////////////////////////////////////////////////	

	function friendUser($args) {
		
		$exists = $this->db->where('user_id_followed=?', $args['followed'])
		->where('user_id_follower=?', $args['follower'])
		->select('users_friends');
		
		if (empty($exists)) {
			$this->db->insert('users_friends', [
				'user_id_followed' => $args['followed'],
				'user_id_follower' => $args['follower'],
			]);	
		} else {
			return 0;
		}
	}
	
	function approveFriend($args) {
		$exists = $this->db->where('user_id_followed=?', $args['followed'])
		->where('user_id_follower=?', $args['follower'])
		->select('users_friends');

		if (empty($exists)) {
			return 0;
		} else {		
			$this->db->where('user_id_followed=?', $args['followed'])
			->where('user_id_follower=?', $args['follower'])
			->update('users_friends', [
						'approved' => 1,
						'new' => 0
			]);			
		}
	}

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

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

	function getFriends($args) {
		// GET THE FRIENDS OF A PARTICULAR USER
		if (isset($args['followed']) && is_numeric($args['followed'])) {
			$this->db->where('user_id_followed=?', $args['followed']);
			$this->db->where('approved=?', 1);
		}
//		if (isset($args['follower']) && is_numeric($args['follower'])) {
//			$this->db->where('user_id_follower=?', $args['follower']);
//		}
		$results = $this->db->select('users_friends');
		return $results;
	}
	// this gets all, included requests
//	function getAllFriends($user_id) {
//		// GET FRIENDS AND REQUESTS INITIATED BY OTHERS
//		//if (isset($user_id) && is_numeric($user_id)) {
//			$this->db->where('approved=?', 0);
//			//$this->db->where("('user_id_followed= $user_id OR user_id_follower = $user_id')");
//		//}
//
//		$results = $this->db->select('users_friends');
//		return $results;
//	}	

	function getAllFriends($user_id) {
		//$this->db->where('user_id_follower=?', $user_id);
		
		//$this->db->where('projects.user_id=?', $user['id']);
		//$this->db->join('projects', 'projects.id=proposals.project_id');
		$this->db->order_by('users_friends.id DESC');
		$this->db->join('users', 'users_friends.user_id_follower=users.id');
		$this->db->where('user_id_followed=?', $user_id);
		//$this->db->where("(user_id_follower = {$user_id} OR user_id_followed = {$user_id})");
		$allfriends = $this->db->select('users_friends');
		return $allfriends;
	}

	function isFriend($args) {
		$exists = $this->db->where('user_id_followed=?', $args['followed'])
			->where('user_id_follower=?', $args['follower'])
			->where('approved=?', 1)
			->select('users_friends');

		//print_r($exists);
		if (!empty($exists)) {
			return 1;
		}
		//return $this->db->affected_rows();
	}	
	
	function isRequested($args) {
		$exists = $this->db->where('user_id_followed=?', $args['followed'])
			->where('user_id_follower=?', $args['follower'])
			->where('approved=?', 0)
			->select('users_friends');

		//print_r($exists);
		if (!empty($exists)) {
			return 1;
		}
		//return $this->db->affected_rows();
	}	

	/////////////////////////////////////////////////////////
	// UPDATING BUMPS, ETC FUNCTIONS START HERE
	/////////////////////////////////////////////////////////

	function showRanks(){
		$this->db->order_by('reward DESC, id ASC');
		$scores = $this->db->select("users",['id','email','name','reward']);
		
//		$i = 1;
//		foreach ($scores as $score) {
//			echo $i . ") " . $score['email'] . " : " . $score['reward'] . "<br />";
//			$i++;
//		}
		
		return $scores;
	}
	
	function updateRanks(){
		//$this->db->order_by('reward DESC, id ASC');
		$this->db->order_by('credits DESC, id ASC');
		$scores = $this->db->select("users",['id','email','name','reward']);
		
		$i = 1;
		foreach ($scores as $score) {
			//echo $i . ") " . $score['email'] . " : " . $score['reward'] . "<br />";
			echo $i . ") " . $score['email'] . " : " . $score['credits'] . "<br />";
			
			// UPDATE RANK
			$this->db->where('id=?', $score['id']);
			$this->db->update('users', ['rank' => $i]);
			$i++;
		}
		
		return $scores;
	}
	
	function updateBumps(){
		
		//$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');

		$bumps = $this->db->select("bumps", ['user_id', 'SUM(value) AS totalpoints']);
		foreach ($bumps as $bump) {
			// UPDATES TOTAL BUMP POINTS - reward field
			$this->db->where('id=?', $bump['user_id']);
			$this->db->update('users', ['reward' => $bump['totalpoints']]);
		}
//		foreach ($users as $index => $u) {
//			if ($u['image'] != '' && !strstr($u['image'], '//')) {
//				$users[$index]['image'] = $this->image_folder . $u['image'];
//			}
//		}

		return $bumps;
		
//		$allUsers = $this->db->select('users');
//		
//		foreach ($allUsers as $allUser) {
//			echo "<br />" . $allUser['name'] . "<br />";
//			$this->db->where('user_id=?', $allUser['id']);
//			$bumps = $this->db->select("bumps");
//			if (!empty($bumps)) {
//				return $bumps;	
//			}
//			//$this->db->update('users', ['refqty' => $refTotal]);
//			//$users = $this->db->select("bumps", ['*', 'SUM(bumps.value) AS total']);
//			//return $users;
//		}
	}
	
	function updateReferrals(){
		$allUsers = $this->db->select('users');
		
		// UPDATES REFERRAL COUNT ref or refcode
		foreach ($allUsers as $allUser) {
			$thisUsersRefs = $this->getReferrals($allUser['ref']);
			//$refTotal = count($thisUsersRefs); // REFERRAL COUNT
			//echo $refTotal . "<br/>";
			if (!empty($thisUsersRefs)) {
				echo "Referrer: " . $allUser['name'] . "<br />";
				foreach ($thisUsersRefs as $thisUsersRef) {
					echo " - " . $thisUsersRef['name'] . " and UserID: " . $thisUsersRef['id'] . "<br />";
					// REWARD THE REFERRER WITH BUMPS
//					$this->db->insert("bumps", array(
//							"action"  		=> 'referral bonus',
//							"value" 		=> 5,
//							"user_id" 		=> $allUser['id'],
//							"email"   		=> $allUser['email'],
//							"description"   => 'referral bonus',
//							"notes"    		=> 'reconcile',
//							"phone"   		=> NULL
//						)
//					);

					// REWARD THE REFERRED WITH BUMPS
//					$this->db->insert("bumps", array(
//							"action"  		=> 'referral accept',
//							"value" 		=> 5,
//							"user_id" 		=> $thisUsersRef['id'],
//							"email"   		=> $thisUsersRef['email'],
//							"description"   => 'referral acceptance bonus',
//							"notes"    		=> 'reconcile for ' . $thisUsersRef['name'],
//							"phone"   		=> NULL
//						)
//					);
				}	
			}
			// UPDATES REFERRAL COUNT
			//$this->db->where('id=?', $allUser['id']);
			//$this->db->update('users', ['refqty' => $refTotal]);
			
		}
	}	
	
	/////////////////////////////////////////////////////////
	// REFERRAL FUNCTIONS START HERE
	/////////////////////////////////////////////////////////
		
	function getReferrals($refcode) {
		$this->db->where('refby=?', $refcode);
		$referrals = $this->db->select('users');
		return $referrals;
	}
	
	function getReferralClicks($refcode){
		$this->db->where('ref_code=?', $refcode);
		$this->db->order_by('id DESC');
		$referralclicks = $this->db->select('referrals');
		return $referralclicks;		
	}
	
	function getReferralEarnings($refcode){
		$totalearnings = $this->db->query('
			SELECT
			COUNT(*)
			FROM users 
			WHERE refby="'.$refcode.'"
			AND is_mem = 1
			AND mem_type = 1 OR mem_type = 4
			')->fetch_row()[0];

		return $totalearnings;
	}	
	
	/////////////////////////////////////////////////////////
	// INTRO FEATURE $string = implode(', ', $tags);
	/////////////////////////////////////////////////////////	
	
    function introduceUsers($user_id,$member_ids){

		$member_ids_string = implode(', ', $member_ids);

        // insert intro
        $this->db->insert("intros", array(
            "user_id"  => $user_id,
			"member_ids" => $member_ids_string,
            "state"    => 0));

        // now notify members - need a foreach here...
        // May need to query the sending user, so we can use their name
        // May need to query the members also, so we can show their info to each other in the Intro
       $notifyModel = new notificationsModel();

			foreach ($member_ids as $member_id) {
				//echo "insert notification for " . $member_id;
		        $notifyModel->insert(array(
					"intro_ids" => $member_ids_string,
					"user_id" => $member_id,
					"from_user_id" => $user_id,
		            "text" => sprintf("Hi, just thought you all should meet. Feel free to start a conversation...", "Intro", $user_id, $user_id)
		        ));
			}
			
			// LOG AN ACTIVITY ALERT SO YOU KNOW YOU SENT IT
				$notifyModel->insert(array(
					"intro_ids" => $member_ids_string,
					"user_id" => $user_id,
					"from_user_id" => $user_id,
					"displayed" => 1,
		            "text" => sprintf("I sent an intro to these members...", "Intro", $user_id, $user_id)
		        ));

//        $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='/project/acceptInvite/%s/%s'>View the project.</a>", $project['title'], $project['id'], $user_id)
//        ));

        return $this->db->insert_id();
    }     
    
    function insertPayment($data){
		$this->db->insert("stripe_payment", array(
			"id" 		=> $data['id'],
			"fullname" 	=> $data['fullname'],
			"email" 	=> $data['email'],
			"item_description" => $data['item_description'],
			"coins"   	=> $data['coins'],
			"amount"  	=> $data['amount'],
			"transaction_id" => $data['transaction_id']
		));
    }  		
    
    function getBalance($user_id) {
		$this->db->where('id=?', $user_id);
        $user = $this->db->select('users')[0];
        
		if (!empty($user)) {
			return $user['virtual_balance'];
        }
    }
    
	/////////////////////////////////////////////////////////
	// CHALLENGES + WINNERS
	/////////////////////////////////////////////////////////

	function getImg($quiz_id){
		$this->db->where("id = ?", $quiz_id);
		$img = $this->db->select('api_trivia');
		return $img;
	}
	
	// Populates Leaderboards  
	function getChallengeImg($challenge_id){
		$this->db->where("id = ?", $challenge_id);
//		$this->db->where("is_active = ?", 1);
//		$this->db->where("hidelb = ?", 0);
		$challenge = $this->db->select('api_challenges');
		return $challenge;
	}
	
	function getLeaderboard($quiz_id){
		$this->db->limit = 500000;
		//$quiz = "McDonalds Voice Trivia";
		//$this->db->where("quiz = ?", $quiz);
		// OLD
//		$this->db->where("qz_id = ?", $quiz_id);
//		//$this->db->order_by("score DESC, rank ASC");
//		$this->db->order_by("score DESC");
//		$results = $this->db->select('api_results');

		// FIRST CHECK IF WE CAN EVEN SHOW THE LEADERBOARD FOR REGULAR TRIVIA QUESTIONS 
		$this->db->where("id = ?", $quiz_id);
		$this->db->where("is_active = ?", 1);
		$challenge = $this->db->select_one('api_challenges');
		if (!empty($challenge)) {
			// WE MAY NEED TO REMOVE THE ANSWERS VAR LATER TO NOT BLOCK TOURNAMENT CHALLENGES
			if ($challenge['hidelb']==1 AND $challenge['answers'] < 10) {
				// THEN ONLY SHOW THE LOGGED USERS' TIME
				if ($_SESSION['user']['id']) {
					$this->db->where("ch_id = ?", $quiz_id);
					$this->db->where("user_id = ?", $_SESSION['user']['id']);
					//$this->db->order_by("score DESC, rank ASC");
					$this->db->order_by("correct DESC, qdate ASC");
					$this->db->join('users', 'users.id = api_shown.user_id');
					//$this->db->join('users', 'users.id=chat.user_id');

					$results = $this->db->select('api_shown', '*, users.email, users.username, users.user_slug, users.image');	
				}
			} else {
				// FOR THE SHOWN TABLE - IE. ANSWER BASED ONLY
				$this->db->where("ch_id = ?", $quiz_id);
				//$this->db->order_by("score DESC, rank ASC");
				$this->db->order_by("correct DESC, qdate ASC");
				$this->db->join('users', 'users.id = api_shown.user_id');
				//$this->db->join('users', 'users.id=chat.user_id');

				$results = $this->db->select('api_shown', '*, users.email, users.username, users.user_slug, users.image');		
			}
		}
		
		//$results = $this->db->select('api_shown');
	
		//$players = $this->db->join('api_results', 'api_results.email = users.email');
		//$this->db->where('refby=?', $refcode);
		
		//$players = $this->db->select('api_results');
		
//		foreach ($players as $index => $u) {
//			$players[$index]['image'] = 'https://voicetrivia.com/static/images/users/agency/default-avatar.jpg';
//			//echo $u['image'];
////			if ($u['image'] != '' && !strstr($u['image'], '//')) {
////				//$zinners[$index]['image'] = $this->image_folder . $u['image'];
////				$players[$index]['image'] = "/static/images/users/agency/" . $u['image'];
////			} else {
////				$players[$index]['image'] = 'https://voicetrivia.com/static/images/users/agency/default-avatar.jpg';
////			}
//		}
		
		return $results;
	}
	
	function getLeaderboards(){
		$this->db->limit = 50;
		//$quiz = "McDonalds Voice Trivia";
		//$this->db->where("quiz = ?", $quiz);
		$this->db->where("parent = ?", 1);
		//$this->db->order_by("score DESC, rank ASC");
		$this->db->order_by("id ASC");
		$leaderboards = $this->db->select('api_trivia');
		return $leaderboards;
	}
	
	function getChallenges(){
		$this->db->limit = 50;
		//$quiz = "McDonalds Voice Trivia";
		//$this->db->where("quiz = ?", $quiz);
		$this->db->where("sched = ?", 1);
		$this->db->where("is_active = ?", 1);
		//$this->db->order_by("score DESC, rank ASC");
		$this->db->order_by("sort ASC");
		$challenges = $this->db->select('api_challenges');
		return $challenges;
	}
	
	// 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;
//	}  
	
	// 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;
//	}

}