<?php

class authsqModel extends baseModel {
    
	//var $salt = 'supersalt';
	// PURE: 'email','password','device_id','device_type','recovery_code','reg_date','is_activated','phone','name','given_name','family_name','image','square_id','token','birthday','virtual_balance','is_verified_phone','verified_date','stripe_id','is_subscribe','local_loyalty_stars','refcode','refby','address','address2','city','state','zip','cross_street','deliv_type','special','bank_account_name','bank_account_type','bank_routing_number','bank_account_number','bank_deposit_amount1','bank_deposit_amount2','bank_verified','bank_verify_tried','reload','lowbal','thresh','loload','weeks','weekly','day','wkload','monthly','date','moload','is_admin','last_distance','device_model','app_version','longitude','latitude','location_lat','location_lng','location_last_lat','location_last_lng','contactless','make','model','color','deviceid','customer_ip','loyalty','ref','usertype','permissions',

	public static $fields = [
		'email','password','device_id','device_type','recovery_code','reg_date','is_activated',
		'phone','name','given_name','family_name','image', 'square_id','token',
		'birthday','virtual_balance','is_verified_phone','verified_date','stripe_id','is_subscribe',
		'local_loyalty_stars','user_slug','username','refcode','refby','ref','address','address2',
		'city','state','zip','cross_street','deliv_type','special','group_id',
		'bank_account_name','bank_account_type','bank_routing_number','bank_account_number',
		'bank_deposit_amount1','bank_deposit_amount2','bank_verified','bank_verify_tried',
		'reload','lowbal','thresh','loload','weeks','weekly','day','wkload','monthly','date','moload',
		'is_admin','last_distance','device_model','app_version','longitude','latitude',
		'location_lat','location_lng','location_last_lat', 'location_last_lng',
		'contactless','make','model','color','deviceid','customer_id','loyalty','usertype','permissions',
		'list_group','first_name','last_name','ver_code','customer_ip', 'x_company','bus_type','occupation_at','acct_type','show_addy','rank','batch','pos','win'
	];    
    
    public $tableName = 'users';
    
    // NOT USING FOR CHATTRBOX / OLD:for square logins that work on the website and in the app(s)
    function getEncryptedPassword($password) {
        $salt = 'square_salt_users15$';
        $pwd = sha1($password . $salt);
        return $pwd;
    }    
    
    // blowfish
    private static $algo = '$2a';
    // cost parameter
    private static $cost = '$10';

    // mainly for internal use
    public static function unique_salt() {
		return substr(sha1(mt_rand()), 0, 22);
    }

    // this will be used to generate a hash
    public static function hash($password) {

		return crypt($password, self::$algo .
			self::$cost .
			'$' . self::unique_salt());
    }
    
    // Generating random Unique MD5 String for user Api key
    private function generateApiKey() {
        return md5(uniqid(rand(), true));
    }

    // this will be used to compare a password against a hash
    public static function check_password($hash, $password) {
		$full_salt = substr($hash, 0, 29);
		$new_hash = crypt($password, $full_salt);
		return ($hash == $new_hash);
    }    
    
	function square_login($email, $password, $remember = 0) {
		if (!$email || !$password) {
			return 0;
		}
		
		$this->db->where('email=?', $email);
		//$this->db->where('password=?', $this->encodePwd($password));
		$this->db->where('type=?', 'native');
		$accounts_matched = $this->db->select('users');
		
//		print_r($accounts_matched);
//		exit;

		if (count($accounts_matched) >= 1) {
			$account = $accounts_matched[0];
			$password_hash = $account['password'];
			if ($this->check_password($password_hash, $password)) {
				$this->_saveCookie($account, $remember);
				
				// NOW UPDATE THE LAST_ACTIVE
				$now = date('Y-m-d H:i:s');
				$this->db->where('email=?', $email);
				$this->db->update('users', ['last_active' => $now]);
				return 1;
			}
		} else {
			return 0;
		}
    } 
    
    function square_loginOLD($email, $password, $remember = 1) {
        if (!$email || !$password) {
            return 0;
        }

        $this->db->where('email=?', $email);
        $this->db->where('password=?', $this->getEncryptedPassword($password));
        
        $accounts_matched = $this->db->select('users');

        if (count($accounts_matched) >= 1) {
            $account = $accounts_matched[0];
            $this->_saveCookie($account, $remember);

            return 1;
        } else {
            return 0;
        }
    } 
    
	function pincode_login($pin_code)
	{
		if (!$pin_code) {
			return 3;
		} 

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

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

		if (count($accounts_matched) >= 1) {
			$account = $accounts_matched[0];
			$this->_saveCookie($account, $remember);

			return 1;
		} else {
			return 0;
		}
	}           
    
    private function _saveCookie($account, $remember = false)
    {
        if  (empty($account)) {
            return false;
        }
        
        $_SESSION['loggedin'] = 1;
        $_SESSION['user_id']  = $account['id'];
        $_SESSION['user']     = $account;
		$_SESSION['user']['usertype']     = $account['usertype'];

        if ($remember) {
            $params = session_get_cookie_params();
            setcookie(session_name(), $_COOKIE[session_name()], time() + 60*60*24*30, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
        } else {
            $params = session_get_cookie_params();
            setcookie(session_name(), $_COOKIE[session_name()], 0, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
        }
        
        return true;
    }

    function checkCode($code) {
        if ($code == '') {
            return 0;
        }
        $this->db->where('recovery_code=?', $code);
        $u = $this->db->select('users');
        if (!empty($u)) {
            return 1;
        } 
    }

    function resetPassword($pwd, $code) {
        if (trim($code) == '') {
            return 0;
        }

        $this->db->where('recovery_code=?', $code);
        
        // NEW
		$this->db->update('users', ['password' => $this->hash($pwd), 'recovery_code' => '']);
		// OLD
        //$this->db->update('users', ['password' => $this->getEncryptedPassword($pwd), 'recovery_code' => '']);
		//$this->db->update('users', ['password' => $this->getEncryptedPassword($pwd), 'address2' => 'Worked']);


		$updated = $this->db->affected_rows();

		if($updated = 1){
			return 1;
		} else {
			//echo "Ooopsie...";
			header("Location: " . get('siteroot') . 'auth/forgot?msg=' . urlencode("Oooops! Something went wrong. Please try again or contact Tech Support on our Contact page."));
		}
		/*
        if ($this->db->affected_rows()) {
            return 1;
        } else { 
			echo "Ooops";
		}*/
    }

    function preparePasswordReset($email) {
        $this->db->where('email=?', $email);
        $u = $this->db->select_one('users');

        if (empty($u))
            return false;

        $code = md5(time() . $u['id'] . rand(0, 100));

        $this->db->where('id=?', $u['id']);
        $this->db->update('users', ['recovery_code' => $code]);

        $u['reset_code'] = $code;

        return $u;
    }

    function availableSlug($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 makeVercode(){
		$length = 7;
		$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

		$string = '';
		$max = strlen($chars) - 1;
		for ($i = 0; $i < $length; $i++) {
			$string .= $chars[mt_rand(0, $max)];
		}
		//$new_code = $string;
		return $string;
    }
    
    function makeUserSlug($fullname) {
		//$user_slug = preg_replace('/[^A-Za-z0-9\-\(\) ]/', '', $_POST['email']);
		
		$prep_user_slug = strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/','', $fullname));
		
		$remove_periods = str_replace(array('.', ','), '' , $prep_user_slug);
		
		$shortened = substr($remove_periods, 0, 5);
		
		$clean_user_slug = stripslashes($shortened);

		// NOW LET'S ADD A 3 CHARACTER UNIQUE ELEMENT
		$length = 3;
		$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

		$string = '';
		$max = strlen($chars) - 1;
		for ($i = 0; $i < $length; $i++) {
			$string .= $chars[mt_rand(0, $max)];
		}
		//echo json_encode($string);
		
		$user_slug = $clean_user_slug . "" . strtolower($string);
		
		return $user_slug;
		
		//print_r($user_slug);
		//exit; 
		          
		//header('Location: /auth/test');
            //exit;
    }

    function register($userdata) {
    	
		//echo "register works...";
//		echo "<pre>";
//		print_r($userdata);
//		exit;
    	
		//$userdata = [];
//		
//		$userdata = [
//			[refby] => devshares [refcode] => demo1234 [usertype] => Consumer [list_group] => [group_id] => [occupation_at] => [bus_type] => [name] => John [email] => demo1234@demo.com [phone] => [password] => demo [g-recaptcha-response] => 03AFcWeA4vi-js-BbIbmfW-AZ8wNEHmxyzF3TfawvJpQN4Y1FhpKS9UD0L2K5h-IfgChiII43jl9awxYqY7Axuxa092okeFJGDdPvE1ql_SNzHNZ0kBSX1iOjSX8mY-MX4GT8CScOxweKOp7K6AX1yDY-AVP9sA4JYGkY36ro7ejq5_EZcjWMFVHTfmgiu1-l6EqYy3uRoMRnX7lkLaGUm8dHdhkmKrIxjVd1wg4zcJdIGw7MwOMHRi1_0qycaw0XsoWd8GdZDiyR_Zw-GSL9b0GyXJnuWk0gIVdUOeGU0x3TXi4PbHSpKsc9kLx9_dUnKgciWxH0Q_oExAMOQOQOpKAm_2-C7xs5Rt43kGzKO0rK9gsSoIPEgmG3vk-e5Nq2KxhpTZke1jvjCLCJmfSPVPYNdAQzP3TNnW4I48d_ohUCU5mrcQVwjyOdY3gDKwLSZppq3B98CJPbcIXNfz-meEpvJLcClaZjc40LUiM2yr_dV3ALr031IMbz9eiLprCHih5k9biVs_EG_wbiS9gc2n3_JdCuJ97MD6Kl8yBvhG_--Gu1VJtOmFDoL6qSaATyaHwofWqJ6lnwrfPHGunqEuYMeA9jQjFpIqAkJFz_SUu0fwHw8cIK3vCFaz_8Irin7bjZFXZL7F4hc8olYsjZBNaztqxuGAViIBr2_7_xfawdgLNLbd2rBBC4o48uzhDwqTpN3NTDYufCEqKO1bwWNWciZ9hWByOOiLoLJ6oGuK8GNl5pyatEqVo78B6v4RAgbviG3pQY3nWRIJbscn1EanXnwVPxHFKiaUoUwH-CoSDH93hf1teqABRqJTaLhCT-1DgOBz7OoD1k1njVgf4HGgzyoBxo0i0dbBPaIQvZgIYnNb6rcxawqZaRPDHf2iynqhTRwh1VBssQahv9_RdY3hNJj2jCQE3mHsLgyQwuSyQCNiT8mM29QAjtq7YvP3nnz-iZ1xmRyhzcJ6ux8ajHKLRb20Xq_nQRhZiIEE8-UqJVaGw7nbHYtRMfgGhIsniDy0Q-blP3qEQVsm1O5654lg8MrvbVRZl3OAw6oa_edUi4KCXGhxQaYBS7OLyOYKRlXhHhLgw9gAKG0PE3odOEf0JAdXFjqDalFv1mTqZlQYweDt0RHNV6hPOjXuaVdJyQ-RzoVltDLRammMMNFI6Sbh7-taJMAjkc7OYVDz0a3PdC5ddWyUWLiqDrZek8SXb7cEwJ5rVvOrffVcdNQ-n_2QDnHp3dVkA8CAhx3wQaDMvzsEgMB76A0m5S3Wj3Aihuzln9Y0iZMJ1RvAucF9qiXJv4Yw8UK7NFrR5wQRs7i9KYxrh_4EPvrXIGOZKdHEwtXwizUo4oj9bAt3ar8FWKiBmjuSfcWvzFMHnQYVuMlBPCyJQRBWSQsRNpf-59Vl8io2n_Tm468XIsnXynC9PU3cI8Uqsm9DW5f0mzh_poYg_t0As_wERgKOxYjYT4JMT4PCyOd_HsYv7xECWve8qgPM6CVBIGAfwE7u-jd4l2Q0T13ukEDPhSUsw3tcmgs5weeL8Q8oYe-1OIwM25Z-Xu20LuLSc8yuXhLnYleE_Ifep1s_S8rHTr5Y_NIza9sAtJemmnWm7T_2UzwBGfAcHHfskCWfN-YThVhtonsQ9mvSX2ws_7Yie5olEw [given_name] => John [family_name] => NA [first_name] => John [last_name] => NA [square_id] => U4JV1MZFJ6PUIU9GCPBM2AMHZV [ver_code] => 1tG2uNZ [customer_ip] => 76.157.245.58 [ref] => demo1234
//		];
//		
//		print_r($userdata);
//		exit;
    	
		if (!$userdata['email'] || !$userdata['password']) {
			header("Location: /");
			exit;
		}

		$lowercase_email = strtolower($userdata['email']);
		$this->db->where("email=?", $lowercase_email);
		$u = $this->db->select("users");
		if (count($u) > 0) {
			header("Location: /auth/register?msg=User+already+exists");
			exit;
		} 
		
		foreach ($userdata as $index => $value) {
			if (!in_array($index, self::$fields)) {
				unset($userdata[$index]);
			}
		}
		
//		echo "here 1...";
//		exit;
		
//		if (!empty($userdata['refby'])) {
//			$this->db->where("ref=?", $userdata['refby']);
//			$this->db->limit(1);
//			$referrer = $this->db->select_one("users","id");
//			//print_r($referrer);
//			
//			if (count($referrer) > 0) {
//				$userdata['org_id'] = $referrer['id'];
//				$userdata['owner'] = $referrer['id'];
//				if (empty($userdata['list_group'])) {
//					$userdata['list_group'] = "all";
//				}
//			}			
//		}

		$userdata['api_key']  = $this->generateApiKey();
		$userdata['password'] = $this->hash($userdata['password']);
		$userdata['email'] = $lowercase_email;
		$username = substr($lowercase_email, 0, strpos($lowercase_email, '@'));
		//$userdata['user_slug'] = $this->availableSlug($username);

		// LET'S SPLIT THE NAME INTO THE 2 NAME FIELDS
//		$name_string = $userdata['name'];
//		$name = explode(" ", $name_string);
//		$userdata['first_name']  = $name[0];
//		$userdata['last_name'] = $name[1];
//		$userdata['given_name']  = $name[0];
//		$userdata['family_name'] = $name[1];
				//echo $name_string . "\n";
		//echo $name[0]  . "\n"; // George
		//echo $name[1]  . "\n"; // Washington
		
		$full_name = $userdata['name'];		
		$parts = explode(" ", $full_name);

		if (count($parts) > 2) {
			$last = array_pop($parts);
			$first= implode(" ", $parts);
		}

		$userdata['first_name']  = $first;
		$userdata['last_name'] 	 = $last;
		$userdata['given_name']  = $first;
		$userdata['family_name'] = $last;
		
		if (empty($userdata['customer_ip'])) {
			// IP ADDRESS
			if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
				//ip from share internet
				$user_ip = $_SERVER['HTTP_CLIENT_IP'];
			} elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
				//ip pass from proxy
				$user_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			} else {
				$user_ip = $_SERVER['REMOTE_ADDR'];
			}

			$userdata['customer_ip'] = $user_ip;	
		}	
		
		$userdata['online'] = 1;
		
		if (empty($userdata['ver_code'])) {
			$userdata['ver_code'] = $this->makeVercode();
		}
		
		// this was user_slug for some reason
		if (empty($userdata['refcode'])) {
			$user_slugg = $this->makeUserSlug($userdata['name']);
			$user_slug = strtolower($user_slugg);

			$userdata['user_slug'] = $user_slug;
			$userdata['username'] = $user_slug; // primarily used by app, so this copies user_slug to it
			$userdata['ref'] = $user_slug;
			$userdata['refcode'] = $user_slug;
		} else {
			$userdata['ref'] = $userdata['refcode'];
			$userdata['user_slug'] = $userdata['refcode'];
			$userdata['username'] = $userdata['refcode'];
		}
		
		$newRanked = $this->getNewRank();
		if (!empty($newRanked)) {
			$userdata['rank'] = $newRanked;	
		}

//		$BatchNo = $this->getLastBatch();
//		if (!empty($BatchNo)) {
//			$SameBatchNo = $BatchNo;
//			$NextBatchNo = $BatchNo + 1;
//		}
//		
//		$Position = $this->getLastPosition();
//		if (!empty($Position)) {
//			if ($Position == 10) {
//				$userdata['pos'] = 1;
//				$userdata['batch'] = $NextBatchNo;
//			} else {
//				if($Position == 9){
//					// THEN WE CAN PICK A WINNER, AS LONG AS WE INCLUDE THIS 10TH MEMBER TOO
//					$winningPosition = $this->pickaWinner();
//					if(!empty($winningPosition)){
//						if ($winningPosition == 10) {
//							$userdata['win'] = 1;
//						} else {
//							$this->db->where('batch=?', $SameBatchNo);
//							$this->db->where('pos=?', $winningPosition);
//							$this->db->update('users', ['win' => 1]);
//						}
//					}
//					
//					// And do a little api_dashupdates entry
//					$this->db->insert("api_dashupdates", [
//						'title' 	=> "New $10 Winner!",
//						'content'	=> "New $10 Winner (highlighted in green)!",
//						'author' 	=> "",
//						'image'  	=> NULL,
//					]);
//				} 
//				$userdata['pos'] = $Position + 1;
//				$userdata['batch'] = $SameBatchNo;			
//			}
//		}		

//		print_r($userdata);
//		exit;

		$this->db->insert('users', $userdata);
		return $this->db->insert_id();
    }
    
    function getDashTotals(){
		//$c = $this->db->where('id=?', 2)
		//->where('displayed=0')
		$dashTotals = $this->db->select('dashtotals');

		return $dashTotals;
	}
    
	function getTotalUsers(){
		//$c = $this->db->where('id=?', 2)
		//->where('displayed=0')
		$totalCurrent = $this->db->select('users', 'COUNT(*) AS c')[0]['c'];

		return $totalCurrent;
	}
    
	function increaseUsers($currTotal){
		$newTotal = $currTotal + 1;
		$id = 2;
		//$this->db->updateDashTotals(2,$data);
		$this->db->where('id=?', $id);
		$this->db->update('dashtotals', ['value' => $newTotal]);
		
//		$getLastUser = $this->db->where('id=?', $id);
//		$this->db->select('users');
		
//		$this->db->where('id=?', $id);
//		return $this->db->select('bumps')[0];

		//$last_drawing_id = mysql_fetch_row(mysql_query("SELECT max(drawing_id) AS drawing_id FROM users_winners ORDER BY id DESC LIMIT 1"));
		
		//mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1
		
		$lastUsersName = $this->getLastUsersName();
		
		// And do a little api_dashupdates entry
		$this->db->insert("api_dashupdates", [
			'title' 	=> "New User!",
			'content'	=> $lastUsersName . " just signed up...",
			'author' 	=> "",
			'image'  	=> NULL,
		]);
		
		//$newTotal = $this->db->select('dashtotals');
		//$newTotal = $this->db->select('users', 'COUNT(*) AS c')[0]['c'];
		
		//return $newTotal[0]['value'];
	}	
	
	function increasePrizePot(){
		$authModel   = new authsqModel();
		$dashTotals = $authModel->getDashTotals();

		if (is_array($dashTotals)) {
			$dashTotals[0]['value'];
			$newPrizePotTotal = $dashTotals[0]['value'] + 10;
			//echo $dashTotals[0]['value']; // PrizePot Total
			//echo $dashTotals[0]['id']; // ID/Row of PrizePot
			
			$this->db->where('id=?', $dashTotals[0]['id']);
			$this->db->update('dashtotals', ['value' => $newPrizePotTotal]);
		}
	}
	
	function getLastUsersName(){
		$this->db->order_by('id DESC');
		$lastUser = $this->db->select_one('users',['user_slug','name','first_name','image']);
		
		//$lastUser = $authsqModel->getLastUser();
		if (!empty($lastUser['first_name'])) {
			$lastUserName = $lastUser['first_name'];
		} elseif (!empty($lastUser['name'])) {
			$lastUserName = $lastUser['name'];
		} else {
			$lastUserName = "A new user";
		}
		
//		$this->db->limit(1);
//		$this->db->select('users');
		return $lastUserName;
	}
    
    function createallgroup($new_user_id){
		// https://chattrboxx.com/auth/register?ref=team&grp=1
		// refcode and ref
		$this->db->insert("groups", [
			'groupname' => "all",
			'type'   	=> "autogroup",
			'link'   	=> "https://flipmob.com/auth/register?ref=".$new_user_id,
			'allgroup'  => 1,
			'owner'  	=> $new_user_id
		]);
		
		//$this->db->insert('campaign', $update_data);
		//$id = $this->db->insert_id(); 
		//return $id;  	
    }

    function registerOLD($userdata) {
		//print_r($userdata);
		//exit;
//    	if (!$userdata['given_name'] || !$userdata['email'] || !$userdata['password']) {
//            header("Location: /dash/register?oops");
//            exit;
//        }

        $this->db->where("email=?", $userdata['email']);
        $u = $this->db->select("users");
        if (count($u) > 0) {
            header("Location: /auth/register?msg=That+User+Account+already+exists");
            exit;
        }
		/*
        foreach ($userdata as $index => $value) {
            if (!in_array($index, self::$fields)) {
                unset($userdata[$index]);
            }
        }*/
		$userdata['ref'] = $userdata['refcode'];
		//$encrypted_pwd = getEncryptedPassword($new_password);
        $userdata['password'] = $this->getEncryptedPassword($userdata['password']);
        $userdata['token'] = sha1($userdata['email'] . "9Tv". time());
        
        //$username = substr($userdata['email'], 0, strpos($userdata['email'], '@'));
        //$userdata['given_name'] = $username;
		
        //$userdata['user_slug'] = $this->availableSlug($username);
    
        $this->db->insert('users', $userdata);
       return $this->db->insert_id();
    }
    
	function subscribe($subscriberdata) {
		if (!$subscriberdata['email']) {
			header("Location: /");
			exit;
		}

		$this->db->where("email=?", $subscriberdata['email']);
		$u = $this->db->select("subscribers");
		if (count($u) > 0) {
			header("Location: /useralreadyexists");
			exit;
		}
        
		$subscriberdata['code'] = mt_rand(1,99999);	
        //$subscriberdata['interestedin'] = $_POST['interestedin'];
		
		$this->db->insert('subscribers', $subscriberdata);
		
		//mail("sillystats@gmail.com", "Subscriber Alert3!", "You have a new Subscriber!", "From: ThinApp <contact@getthinapp.com>");
	}	    
    
    // GET USER
    function getUser($uid) {
        $this->db->where("id=?", $uid);
        $user = $this->db->select_one('users');

        return $user;
    }    
    
    function getNewRank(){
		$lastRank = $this->db->select_one('users', 'MAX(rank) as last');
		if (!empty($lastRank)) {
			$newRank = (int)$lastRank['last'] + 1;
			return $newRank;
		} else {
			return 0;
		}
    }
    
	function getLastBatch(){
		$lastBatch = $this->db->select_one('users', 'MAX(batch) as last');
		if (!empty($lastBatch)) {
			$lastBatchNum = (int)$lastBatch['last'];
			return $lastBatchNum;
		} else {
			return 0;
		}
	}
	
	function getLastPosition(){
		$lastBatch = $this->getLastBatch();
		$this->db->where("batch=?", $lastBatch);
		$lastPosition = $this->db->select_one('users', 'MAX(pos) as last');
		if (!empty($lastPosition)) {
			$lastPosNum = (int)$lastPosition['last'];
			return $lastPosNum;
		}
	}
	
	function pickaWinner(){
		$randomIndex = mt_rand(1, 10);
		return $randomIndex;
	}
	
	function checkifweshouldpickaWinner(){
		$lastBatch = $this->getLastBatch();
		$this->db->where("batch=?", $lastBatch);
		$lastPosition = $this->db->select_one('users', 'MAX(pos) as last');
		if (!empty($lastPosition)) {
			$lastPosNum = (int)$lastPosition['last'];
			
			if ($lastPosNum==10) {
				// we should really check for a winner first
				$this->db->where('batch=?', $lastBatch);
				$this->db->where('win=?', 1);
				$checkWinner = $this->db->select_one('users');
				
				if (!empty($checkWinner)) {
					echo "Already have a Winner";
					return;
				}
				//echo "check return";
				
				$winner = $this->pickaWinner();
				//echo $winner . " is the new Winner";
				$this->db->where('batch=?', $lastBatch);
				$this->db->where('super=?', 'VIP');
				$this->db->where('actives=?', 1);
				$this->db->where('pos=?', $winner);
				$this->db->update('users', ['win' => 1]);
				
				// And do a little api_dashupdates entry
				$this->db->insert("api_dashupdates", [
					'title' 	=> "New $10 Winner!",
					'content'	=> "New $10 Winner for Batch " . $lastBatch . " (highlighted in green)!",
					'author' 	=> "",
					'image'  	=> NULL,
				]);
				
				return "The Batch " . $lastBatch . " Winner is User #" . $winner;
			}
		}
		
	}
	
	function testfunction(){
		//$vipplan = "vip_548612553";
		$vipplan = "Lifetime VIP Membership - $.01";
		$vipstring = substr($vipplan,0,23); // 0, 3 for VIP
		return $vipstring;
	}
    
	// CONVERT A MYSQLI RESULT OBJECT TO AN ARRAY
	function getArrayFromSqlList($r)
	{
		if (empty($r)) {
			return [];
		}

		$output = array();
		while ($row = mysqli_fetch_assoc($r)) {
			$output[] = $row;
		}

		return $output;
	}	
    
}