<?php

class squareuserModel extends baseModel {

    public $tableName = 'usersslim';
    
	const FAVTYPE_OBJECT  = 1;
	const FAVTYPE_PROJECT = 2;
	const FAVTYPE_GROUP   = 3;
	const FAVTYPE_USER    = 4;
	const FAVTYPE_PRODUCT = 5;
	const FAVTYPE_LISTING = 6;

	public $image_folder = "/static/images/users/agency/";
	
	static public $fields = [
		'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_activated', 'specific_fee', 'account_type',
		'category_id', 'type_id', 'contact_name', 'contact_email', 'contact_phone', 'contact_best_time', 
		'mailing_address','mailing_address2','directory','creditcard','profilebg',
		'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',
		'max_daily_alerts', 'image', 'user_push_id','reg_date','square_id','birthday','virtual_balance',
		'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',
		'fbonus','fqty','fbon','fbal','fup'
	];	
	
	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('usersslim');

		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(usersslim.location_lat, ',', usersslim.location_lng) as coordinates",
        	"concat(usersslim.location_last_lat, ',', usersslim.location_last_lng) as last_coordinates",
        	"usersslim.location_lat as location_lat",
        	"usersslim.location_lng as location_lng",
        	"usersslim.location_last_lat as location_last_lat",
        	"usersslim.location_last_lng as location_last_lng",
        ];
        $user['user_location'] = $this->db->where("id = ?", $user['id'])
	         							  ->select_one("usersslim", $location_fields);

//	    $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('usersslim')[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('usersslim', ['id', 'name']);
			return $users;
		} else {
			$users = $this->db->select('usersslim');
		}
		
		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']);		
		// 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('usersslim');	
		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']);
		
			if (!empty($membs)) {
				$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']) && !empty($memList)) {
			$this->db->where("(
					org_id = {$cond['client_id']}
					OR id = {$_SESSION['user']['id']}
					OR id IN($memList)
				)
			");
		} else {
			$this->db->where("(
					org_id = {$cond['client_id']}
					OR id = {$_SESSION['user']['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']);
		// 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('usersslim');
		return $users;		
	}

    function getSquareUser($id) {
        $this->db->where('id=?', $id);
        return $this->db->select('usersslim')[0];
    }
    
    function getAccount($username) {
		$this->db->where('user_slug=?', $username);
        return $this->db->select('usersslim')[0];
    }
    
    function getSubscriber($id) {
        $this->db->where('ver_code=?', $id);
        return $this->db->select('usersslim')[0];
    }
    
    function getUserContactDetails($id) {
        $this->db->where('id=?', $id);
        return $this->db->select('usersslim',['id','email','phone','is_subscribe','is_text','is_push','user_push_id'])[0];
    }    
    function markHidden($id,$checked) {
        $this->db->where('id=?', $id);
        $this->db->update('usersslim', ['is_excluded' => $checked]);
    }

    function updateSquareUser($user_id, $data, $files = []) {
    	
		$currentUserInfo = $this->db->where('id=?', $user_id)->select_one('usersslim');
		
		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('usersslim', ['image' => $new_filename]);
			}
		}	
		
		$data_to_update = $data;
        
		$this->db->where('id=?', $user_id);
		$this->db->update('usersslim', $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('usersslim');

//		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'])) {
				$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('usersslim', ['image' => $new_filename]);
			}
		}
		
		if ($files && $files['profilebg']) {
			$old_bgfilename = $files['profilebg']['name'];
			$extbg = substr($old_bgfilename, strrpos($old_bgfilename, '.')+1);
			
			$new_bgfilename = $user_id . "-" . time() . "." . $extbg;

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

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

				$this->db->where('id=?', $user_id);
				$this->db->update('usersslim', ['profilebg' => $new_bgfilename]);
			}
		}
		
		// APP ICON
		if ($files && $files['x_adress']) {
			$old_app_icon = $files['x_adress']['name'];
			$ext = substr($old_app_icon, strrpos($old_app_icon, '.')+1);
			$new_app_icon = $user_id . "-" . time() . "." . $ext;

			if (in_array($ext, ['png', 'jpg', 'jpeg', 'gif'])) {
				$user = $this->getUser($user_id);
				@unlink($user['x_adress']);
				$new_path = "static/images/appicons/" . $new_app_icon;
				move_uploaded_file($files['x_adress']['tmp_name'], 'static/images/appicons/' . $new_app_icon);

				$this->db->where('id=?', $user_id);
				$this->db->update('usersslim', ['x_adress' => $new_path]);
			}
		}	
		
		// SPLASH IMG FULL SCREEN
		if ($files && $files['x_fax']) {
			$old_splash = $files['x_fax']['name'];
			$ext = substr($old_splash, strrpos($old_splash, '.')+1);
			$new_splash = $user_id . "-" . time() . "." . $ext;

			if (in_array($ext, ['png', 'jpg', 'jpeg', 'gif'])) {
				$user = $this->getUser($user_id);
				@unlink($user['x_fax']);
				$new_splash_path = "static/images/appsplash/" . $new_splash;
				move_uploaded_file($files['x_fax']['tmp_name'], 'static/images/appsplash/' . $new_splash);

				$this->db->where('id=?', $user_id);
				$this->db->update('usersslim', ['x_fax' => $new_splash_path]);
			}
		}		

		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['directory'] = !empty($data['directory']) ? 1 : 0;
		$data['external_id'] = !empty($data['external_id']) ? 1 : 0;
		$data['fbon'] = !empty($data['fbon']) ? 1 : 0;
		$data['fup'] = !empty($data['fup']) ? 1 : 0;
		
//		if ($data['fup'] == 1) {
//			unset($data['fbal']);
//		}
		
//		unset($data['fbal']);
//		echo "<pre>";
//		print_r($data);

		$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('usersslim', $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('usersslim', $data);
    }
    
    function insertSquareUsercropped($id, $img) {
        
        $squarecat = $this->db->where("id = ?", $id)
                          ->select_one("usersslim");    

        $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('usersslim', ['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('usersslim');
    }

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

    function getItem($id) {
        $this->db->where('id=?', $id);
        return $this->db->select('usersslim')[0];
    }
    
	function updateUserLastLocation($user_id, $lat, $lng ){
		$currentUserInfo = $this->db->where('id=?', $user_id)->select_one('usersslim');

		$this->db->where('id=?', $user_id)->update('usersslim', [
			'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('usersslim');

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

		return $total;
	}
	
	function TotalEmployees($client_id){
		$total = $this->db->query('
			SELECT
			COUNT(*)
			FROM
			usersslim 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('usersslim');

		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('usersslim');

		return $users;
	}	
	
	/////////////////////////////////////////////////////////
	// FOLLOWERS FUNCTIONS START HERE
	/////////////////////////////////////////////////////////
	
	function followMe($usertofollow){
		$users = $this->db->select('usersslim');
		
		foreach ($usersslim as $user) {
			$this->followUser([
				'follower' => $user['id'],
				'followed' => $usertofollow
			]);		
//			echo "User to follow: " . $user['id'];
//			echo "Me: " . $args['follower'];
		}
		
//		$exists = $this->db->where('user_id_followed=?', $args['followed'])
//		->where('user_id_follower=?', $args['follower'])
//		->select('users_followed');
	}

	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
		}
	}
		
	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 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;
	}
	
	/////////////////////////////////////////////////////////
	// 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('usersslim', 'users_friends.user_id_follower=usersslim.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();
	}	
	
	/////////////////////////////////////////////////////////
	// REFERRAL FUNCTIONS START HERE
	/////////////////////////////////////////////////////////
		
	function getReferrals($refcode) {
		$this->db->where('refby=?', $refcode);
		$referrals = $this->db->select('usersslim');
		return $referrals;
	}
	
	function getReferralEarnings($refcode){
		$totalearnings = $this->db->query('
			SELECT
			COUNT(*)
			FROM usersslim 
			WHERE refby="'.$refcode.'"
			AND is_mem = 1
			AND mem_type = 1 OR mem_type = 4
			')->fetch_row()[0];

		return $totalearnings;
	}
	
	/////////////////////////////////////////////////////////
	// DRAWINGS, ETC FUNCTIONS START HERE
	/////////////////////////////////////////////////////////	
	
	function getLeaderboard() {
	    $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('usersslim', '*');
	    
		//$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://flipmob.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('usersslim');

        $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://flipmob.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 = usersslim.id');
		$zinners = $this->db->select('usersslim');                    

        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://chattrboxx.com/static/images/users/agency/default-avatar.jpg';
            }
        }

        return $zinners;
    } 
    
	function getRandomThumbs() {
		$this->db->limit = 10;
		$this->db->order_by("reg_date DESC");
		//$this->db->order_by("RAND()");
		$thumbs = $this->db->where('image != ?', '')
			->where('image != ?', 'default-avatar.jpg')
			->select('usersslim', '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 getJoinerThumbs($challenge_id) {
		//$this->db->limit = 5;
		$this->db->where('post = ?', $challenge_id);
		$this->db->order_by("challengers.date DESC");
		//$thumbs = $this->db->select('challengers');
		//$this->db->order_by("challengers.date DESC");
		$this->db->join('usersslim', 'challengers.user_id=usersslim.id');
		$thumbs = $this->db->select('challengers', 'usersslim.id,usersslim.user_slug, usersslim.name, usersslim.image');

		return $thumbs;
	}   	  
    
//	function randomExamples(){
//		$no_of_digits = 100;
//
//		$var='';
//
//		for ($i=1; $i <= $no_of_digits; $i++) {
//
//			$var .=rand(0,99).'<br>';
//
//		}
//		echo "<br>Random Value = <br> $var";	
//		
//		/////////////////////////
//		
//		int random_int ( int $min , int $max );
//		$random_number = random_int(1, 100);	
//	}         	
}