<?php
// THIS IS THE MAIN FILE AND CONTROLS AUTHENTICATION FOR THE 'USERS' TABLE CURRENTLY
// WE ARE WORKING ON MERGING IT WITH AUTH AND MAKING SURE ONLY ONE IS REFERENCES THROUGHOUT CODE BASE
class AuthSQController extends baseController
{
    function validURI($uri)
    {
        return false === strpos("https://", $uri);
    }

    function index() {
    	
        if ($_POST) {
            $authsqModel = new authsqModel();

            //$red irect_to = get('siteroot');
            //$redirect_to = get('siteroot') . 'home/';
            $redirect_to = get('siteroot') . '';
            if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
                $redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");

				if (!empty($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] !=="https://base.basepages.com/") {
				$referrer_page = $_SERVER['HTTP_REFERER'];
			} else {
				$referrer_page = "/profile/edit";
			}
//			print_r($_POST);
//			exit;

//			$loggedin = $authsqModel->square_login($_POST['email'], $_POST['password']);
//			
//			print_r($loggedin);
//			exit;
            
            if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
                //echo "Success!";
                
				//header("Location: https://base.basepages.com");
				//exit;
                
				if (isset($_GET['r'])) {
					
					//header("Location: /auth/register?ref=".$_GET['r']);
					header("Location: /auth/register?ref=".$_GET['r']);
					exit;               	
                } else {
					if (!empty($referrer_page) && $referrer_page !="https://base.basepages.com/auth/login") {
						header("Location: $referrer_page");
						exit;
                	} else {
						header("Location: /profile/edit");
						//header("Location: /leaderboards");
						//$redirect_to = get('siteroot') . 'leaderboards';
						exit;               		
                	}              	
                }
                
            } else {
                //echo "Fail";
                $msg = "Wrong password";
                require 'views/auth/login.tpl.php';
            }
        }
        
        // IF GET - THIS HELPS AUTO-LOGIN USERS FROM THE APPWRAPPER NATIVE MOBILE APPS
		// https://base.basepages.com/auth/login?email=demo@demo.com&password=demo
		if ($_GET['email']) {
			$authsqModel = new authsqModel();
            
			$_POST['email'] = $_GET['email'];
			$_POST['password'] = $_GET['password'];
            
            //$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . 'clients/dashboard';
			$redirect_to = get('siteroot') . 'membership';
			//$redirect_to = get('siteroot') . '';
            //if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
                //$redirect_to = rtrim(get('siteroot'), "/manage/") . "/" . ltrim($_POST['redirect_me'], "/manage/");
				//$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");
				if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
            //if ($authModel->login($_GET['email'], $_GET['password'], isset($_GET['remember']))) {
                header("Location: " . $redirect_to);
                exit;     
            } else {
				$msg = "Something went wrong, please go back and try to access this page again or let support know. Thanks! - Tech Support";
                require 'views/auth/login.tpl.php';
            }       
        }              
          
        // END OF GET
        require 'views/auth/login.tpl.php';   
    }
    
	function loginXXX(){
		if ($_POST) {
			$authsqModel = new authsqModel();

			$_POST['email'] = $_GET['email'];
			$_POST['password'] = $_GET['password'];

			//$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . 'clients/';
			//$redirect_to = get('siteroot') . 'clients/postnew';
			//$redirect_to = get('siteroot') . 'membership';
			$redirect_to = get('siteroot') . 'leaderboards';
			//$redirect_to = 'https://base.basepages.com/clients/';
			//$redirect_to = get('siteroot') . 'project/addnew';
			//$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . '';
			//if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
			//$redirect_to = rtrim(get('siteroot'), "/manage/") . "/" . ltrim($_POST['redirect_me'], "/manage/");
			//$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");
			if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
				//if ($authModel->login($_GET['email'], $_GET['password'], isset($_GET['remember']))) {
				header("Location: " . $redirect_to);
				exit;
			} else {
				$msg = "Something went wrong, please go back and try to access this page again or let support know. Thanks! - Tech Support";
				header("Location: /auth/login?msg=Error Logging In");
				exit;
				//require 'views/auth/login.tpl.php';
			}
		}

		// END OF GET
		require 'views/auth/login.tpl.php';
	}   
    
    function loginn() {
        // IF GET
		// https://base.basepages.com/auth/loginn?email=demo@demo.com&password=demo123
		if ($_GET) {
			$authsqModel = new authsqModel();
            
			$_POST['email'] = $_GET['email'];
			$_POST['password'] = $_GET['password'];
            
            //$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . 'clients/';
			$redirect_to = get('siteroot') . 'clients/postnew';
			//$redirect_to = 'https://base.basepages.com/clients/';
			//$redirect_to = get('siteroot') . 'project/addnew';
			//$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . '';
            //if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
                //$redirect_to = rtrim(get('siteroot'), "/manage/") . "/" . ltrim($_POST['redirect_me'], "/manage/");
				//$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");
				if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
            //if ($authModel->login($_GET['email'], $_GET['password'], isset($_GET['remember']))) {
                header("Location: " . $redirect_to);
                exit;     
            } else {
				$msg = "Something went wrong, please go back and try to access this page again or let support know. Thanks! - Tech Support";
				header("Location: /auth/login?msg=Error Logging In");
				exit;
                //require 'views/auth/login.tpl.php';
            }       
        }              
          
        // END OF GET
        require 'views/auth/login.tpl.php';   
    }    
    
    function loginms() {
        // IF GET
		// https://base.basepages.com/auth/loginms?email=demo@demo.com&password=demo
		if ($_GET) {
			$authsqModel = new authsqModel();
            
			$_POST['email'] = $_GET['email'];
			$_POST['password'] = $_GET['password'];
            
            //$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . 'managed-services/';
			$redirect_to = get('siteroot') . 'clients/ai';
			//$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . '';
            //if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
                //$redirect_to = rtrim(get('siteroot'), "/manage/") . "/" . ltrim($_POST['redirect_me'], "/manage/");
				//$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");
				if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
            //if ($authModel->login($_GET['email'], $_GET['password'], isset($_GET['remember']))) {
                header("Location: " . $redirect_to);
                exit;     
            } else {
				$msg = "Something went wrong, please go back and try to access this page again or let support know. Thanks! - Tech Support";
                require 'views/auth/login.tpl.php';
            }       
        }              
          
        // END OF GET
        require 'views/auth/login.tpl.php';   
    }  
    
    function loginprofile() {
//		echo "works";
//		exit;
        // IF GET
		// https://base.basepages.com/auth/loginprofile?email=demo@demo.com&password=demo123
		if ($_GET) {
//			echo "GET works";
//			exit;
			$authsqModel = new authsqModel();
            
			$_POST['email'] = $_GET['email'];
			$_POST['password'] = $_GET['password'];
            
            //$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . 'managed-services/';
			$redirect_to = get('siteroot') . 'clients/dashboard';
			//$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . '';
            //if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
                //$redirect_to = rtrim(get('siteroot'), "/manage/") . "/" . ltrim($_POST['redirect_me'], "/manage/");
				//$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");
				if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
//				echo "LOGIN works";
//				exit;
                //header("Location: https://base.basepages.com/clients/dashboard");
				header("Location: " . $redirect_to);
                exit;     
            } else {
				$msg = "Something went wrong, please go back and try to access this page again or let support know. Thanks! - Tech Support";
                require 'views/auth/login.tpl.php';
            }       
        }              
          
        // END OF GET
        require 'views/auth/login.tpl.php';   
    }      
    
    function loginpost() {
        // IF GET
		// https://base.basepages.com/auth/loginpost?email=demo@demo.com&password=demo123
		if ($_GET) {
			$authsqModel = new authsqModel();
            
			$_POST['email'] = $_GET['email'];
			$_POST['password'] = $_GET['password'];
            
            //$redirect_to = get('siteroot') . 'profile/edit';
			$redirect_to = get('siteroot') . 'project/addnew/';
			//$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . '';
            //if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
                //$redirect_to = rtrim(get('siteroot'), "/manage/") . "/" . ltrim($_POST['redirect_me'], "/manage/");
				//$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");
				if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
            //if ($authModel->login($_GET['email'], $_GET['password'], isset($_GET['remember']))) {
                header("Location: " . $redirect_to);
                exit;     
            } else {
				$msg = "Something went wrong, please go back and try to access this page again or let support know. Thanks! - Tech Support";
                require 'views/auth/login.tpl.php';
            }       
        }              
          
        // END OF GET
        require 'views/auth/login.tpl.php';   
    }
    
    function loginalerts() {
        // IF GET
		// https://base.basepages.com/auth/loginalerts?email=demo@demo.com&password=demo123
		if ($_GET) {
			$authsqModel = new authsqModel();
            
			$_POST['email'] = $_GET['email'];
			$_POST['password'] = $_GET['password'];
            
            //$redirect_to = get('siteroot') . 'profile/edit';
			$redirect_to = get('siteroot') . 'clients/alerts';
			//$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . '';
            //if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
                //$redirect_to = rtrim(get('siteroot'), "/manage/") . "/" . ltrim($_POST['redirect_me'], "/manage/");
				//$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");
				if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
            //if ($authModel->login($_GET['email'], $_GET['password'], isset($_GET['remember']))) {
                header("Location: " . $redirect_to);
                exit;     
            } else {
				$msg = "Something went wrong, please go back and try to access this page again or let support know. Thanks! - Tech Support";
                require 'views/auth/login.tpl.php';
            }       
        }              
          
        // END OF GET
        require 'views/auth/login.tpl.php';   
    }    
    
    function loginlistings() {
        // IF GET
		// https://base.basepages.com/auth/loginlistings?email=demo@demo.com&password=demo123
		if ($_GET) {
			$authsqModel = new authsqModel();
            
			$_POST['email'] = $_GET['email'];
			$_POST['password'] = $_GET['password'];
            
            //$redirect_to = get('siteroot') . 'profile/edit';
			$redirect_to = get('siteroot') . 'category/all';
			//$redirect_to = get('siteroot') . 'profile/edit';
			//$redirect_to = get('siteroot') . '';
            //if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
                //$redirect_to = rtrim(get('siteroot'), "/manage/") . "/" . ltrim($_POST['redirect_me'], "/manage/");
				//$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");
				if ($authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']))) {
            //if ($authModel->login($_GET['email'], $_GET['password'], isset($_GET['remember']))) {
                header("Location: " . $redirect_to);
                exit;     
            } else {
				$msg = "Something went wrong, please go back and try to access this page again or let support know. Thanks! - Tech Support";
                require 'views/auth/login.tpl.php';
            }       
        }              
          
        // END OF GET
        require 'views/auth/login.tpl.php';   
    }    
    
    function makeCustID() {
			$length = 26;
			$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

			$string = '';
			$max = strlen($chars) - 1;
			for ($i = 0; $i < $length; $i++) {
				$string .= $chars[mt_rand(0, $max)];
			}
			
			//echo $string;
			//echo json_encode($string);
			return $string;
    }   
    
    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 register() {
		header('Location: /auth/join');
		
		//$groupsModel = new groupsModel();
		$authsqModel = new authsqModel();
		
		if ($_POST) {
			if (!empty($_POST['location_lat']) && !empty($_POST['location_lng'])) {
				// make sure we save last location as well.
				$_POST['location_last_lat'] = $_POST['location_lat'];
				$_POST['location_last_lng'] = $_POST['location_lng'];
			}
            
			//$_POST['given_name'] = $_POST['name'];
			
			$parts = explode(" ", trim($_POST['name']));
			$num = count($parts);
			if ($num > 1) {
				$lastname = array_pop($parts);
			} else {
				$lastname = 'NA';
			}
			$firstname = implode(" ", $parts);
			//return array($firstname, $lastname);			
			
			$_POST['given_name'] = $firstname;
			$_POST['family_name'] = $lastname;
			
			// APP 
			$_POST['first_name'] = $firstname;
			$_POST['last_name'] = $lastname;
			
			$_POST['square_id'] = $this->makeCustID();
			
			// VERIFICATION CODE
			$_POST['ver_code'] = $this->makeVercode();
			// OLD sha1("ChattrBoXX-" . time() . $_POST['email']);
			
			// 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'];
			}
			
			$_POST['customer_ip'] = $user_ip;	
			
			$_POST['ref'] = $_POST['refcode']; // ref is used by app, so this copies refcode to ref			
//			print_r($_POST);
//			exit;
            //$authsqModel->register($_POST);
            
			//$user_slug = preg_replace('/[^A-Za-z0-9\-\(\) ]/', '', $_POST['name']);
            
            $user_id = $authsqModel->register($_POST); 
			            
            //$authsqModel->square_login($_POST['email'], $_POST['password']);
			$authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']));            
			header('Location: /auth/register?reg_ok');
            exit;
        }
        
		// DETECT IF THE REF CODE IS IN A GET PARAMETER IN THE LINK
//		if (isset($_GET['ref']) || ) {
//			//echo "Referrer detection works...";
//		}       
//		
		if (isset($_GET['ref'])) {
			// IF REFERRAL COOKIE EXISTS, GET THEIR NAME TO PERSONALIZE THE INVITE
			$refcode = $_GET['ref'];
			$referrer_name = $this->getRefName($refcode);
		} elseif (getReferralFromCookie()) {
			// IF REFERRAL COOKIE EXISTS, GET THEIR NAME TO PERSONALIZE THE INVITE
			$refcode = getReferralFromCookie();
			$referrer_name = $this->getRefName($refcode);		
		}
		
		if (isset($_GET['clear'])) {
			$_SESSION['ref'] = '';
			unset($_SESSION['ref']);
			header("Location: /membership");
			exit;
		}
        
        require 'views/auth/register.tpl.php';
    }
    
    function captcha(){	
		//$token = "test-token";
		$token = "03AFcWeA7F5H8vCnov-l8RoO9a9oNUwuFXofDjO8NRtTnOOR0aGuIYaoJU60hovOeR-tUEpu16b1JfYjwKuAl9arsSxDQVdBhlOg4fo_0T1tq_whjv5JrKOAGUvsK8vdWAsXlSSq4tJw2cn9On3NtJEja1TND5CgCi_7zVXViIm0lBSGs6_jWkqWKaNe9AY34P8FnyTUTu1WBkyrLEzQTY6_GsoFTusHx5Nduzr8QPHD75DpxJW_cDhIQzYsXqXv5_M4_YDm1hXI3gklQk2UOQz1fC7C3_MxQTMfdCztLxFebClz7N5P9-IyFdEn5_zvQjW9I-Tdr_3UoI1HXC9D4b_IV2z7m6zng9ytMwrXvdoI7tDW422UgdRINesTRjrHLIHiAqF2jAQr9y3B5XWw0BJTXM4QtGU5PGaCOOHyGBvuCX4K97W8ScVTlDJrJWl0GVS_ID7B56tWJXFaM66O5ps_5fTh1jxYXdPspl32ehfGItSNqwRsjkhl0I6b2s-qcG3QY4mWiaUzO5a1dbau6PtzexBWp_r-p2XBQXiIjPAitOII9hwwWm4cSxGADJT4XN9FYh6yj_yaWS8yCTTNSh_3B9-W4bNNjZ32XhUSWPu8c7cNTnmO4hEI_bBljiJ2F4HC6qmmmR4DfRq-ZwSEaHUw9OaVmXltjHy5My_LosoYHUCITnWIMWx8jRdK9ZjXVDaMqxW2sT-1VXqaS09Uin3QIykm4k94ufWjDVouKMKcl3MxGh0VWzjVPfRabmk_PkwCHvFEpe2Q3ZszD8t-QVXmiZP2A8NoAu5Q9oL5Dg03cKx4B2eoI1bko4asXW5xaJYeTKijzDyPV4RQZuGXU3IhR7iMi4Arv3zrvMQ5mELwxj1jBDbZye0Y_tFgx8uEteapVqdujMbWidQt4MdBbioCb0VJ4W3MvOUXFeuPQTkkFrTr_i-cKvZomCROIJ5p6fQcJHmBEkS4DR9rLEa_lrYytDH4iOQqoPQHxM658p-qGMN89GllXLy62R868JRnenh2hEQc3GQPTVOH_xPR1gsI2hhJYL7h0nnZwxgnp7agdixSo82QIpZCWv7CUNj_M-Y_XYudUMfkmBKX5OKvxCGWHy2IVazj4fFH5y0uTYOzn2af1iMzRYa_EILREzvjtBTF_7_2GxkwK2XcI1Pz77cyTNwlwTNmSmZRH-juL9mZuM3e-OaJbaGETz8zQRbZpf9nHD_i1aybyUsQJW-uWjJAiuHHFN238Q0U8EuPOLKfXfhN_3j7wbzn-PJIVjo6wDcIz1xs-14SBOiW-uh_nHvWguX8N7uTnRguiWEi8AC9EndDa5yMh64pknXvW3BzkFVn9kOYHMMHx2fye5VlrlpY4yhOvLvwiS0ze5hdaQqH1KoLGiPe5cGLMTpX22yKGCgz0cmeOvQjHNvkK1ypR1JP9FJ0a8tyS8ryv8WirVwB9_TUVGd0sBkaTH2e9gBKmImDknrGn_lKVxFWvhlhbcqIAnpnBgFLwBYBDPeJrerKYv5fEF7IgYU6Qz7NOBBdelL6svdjMlMLxZGf64lc3sDoeLjtta-HFQ5a3IVY0Lj5xegjomEbKSeQZW58b1AxZD9AqxUrcyqfddDzlfAkxFQc7nWxcEwDg5PF0BtJ7lJ6XKM9Q8mf0Qfwbc_ap8bzs1A1w5bgIWEOVXnO7a5kCgrVBw2FDEfdWyfg";
		//echo $token;
		//echo "works...captcha verify";
		// call curl to POST request
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => '6LcfnVopAAAAAO9N92-T-OTPo24n8Nd7Y_R31Gcv', 'response' => $token)));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($ch);
		curl_close($ch);
		$arrResponse = json_decode($response, true);
		
		print_r($arrResponse);

		// verify the response
		if ($arrResponse["success"] == '1' && $arrResponse["score"] >= 0.5) {
			return true;
			echo "Success!";
		} else {
			return false;
			echo "false";
		}
	}  
    
	function captchaTokenVerify($token){	
		//echo "works...captcha verify";
		// call curl to POST request
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => '6LcfnVopAAAAAO9N92-T-OTPo24n8Nd7Y_R31Gcv', 'response' => $token)));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($ch);
		curl_close($ch);
		$arrResponse = json_decode($response, true);

		// verify the response
		if ($arrResponse["success"] == '1' && $arrResponse["score"] >= 0.5) {
			return true;
			//return $arrResponse;
		} else {
			return false;
			//return 0;
		}
	}  
	
	// UPDATE RANKINGS RANKS https://base.basepages.com/auth/inc
	function inc(){
		$squareusersModel = new squareusersModel();
		
//		$showReferrals = $squareusersModel->updateReferrals();
//		print_r($showReferrals);
//		exit;

		$showRankings = $squareusersModel->updateRanks();
		echo "<pre>";
		print_r($showRankings);
		exit;
		
		// UPDATE BUMPS
//		$showBumpTotals = $squareusersModel->updateBumps();
//		echo "<pre>";
//		print_r($showBumpTotals);
//		exit;
		
		$authsqModel = new authsqModel();
		$totalMembers = $authsqModel->getTotalUsers();
		if ($totalMembers) {
			$authsqModel->increaseUsers($totalMembers);
		}
	}
    // THIS IS THE MAIN SIGN UP FORM/PAGE AT /AUTH/JOIN
   	function join() {
   		// IF THE USER IS ALREADY LOGGED IN REDIRECT THEM TO THE EDIT ACCOUNT PAGE
   		if ($_SESSION['loggedin'] && isset($_SESSION['user'])) {
			//echo "Logged in!";
			header("Location: /profile/edit");
			exit; 
		}
		//$groupsModel = new groupsModel();
		$authsqModel = new authsqModel();
		$squareuserModel = new squareusersModel();
		
		//echo "CaptchaResult: " . captchaTokenVerify($_POST['g-recaptcha-response']);
		// was just this if ($_POST) { before I tried to protect the sign up form with captcha
		if ($_POST && isset($_POST['g-recaptcha-response'])) {
		//if ($_POST) {
			$checkToken = $this->captchaTokenVerify($_POST['g-recaptcha-response']);
			//$checkToken = 1;
			if ($checkToken == 1) {
				//echo "The sign up should work...";
				//$honeypot = FALSE;
				if (!empty($_REQUEST['lastname']) && (bool) $_REQUEST['lastname'] == TRUE) {
					//echo "SPAM";
					return;
					//$honeypot = TRUE;
					//log_spambot($_REQUEST);
					# treat as spambot
				} 
//				else {
//					echo "Allow sign up";
//					# process as normal
//				}
				
				if (!empty($_POST['location_lat']) && !empty($_POST['location_lng'])) {
					// make sure we save last location as well.
					$_POST['location_last_lat'] = $_POST['location_lat'];
					$_POST['location_last_lng'] = $_POST['location_lng'];
				}

				//$_POST['given_name'] = $_POST['name'];

				$parts = explode(" ", trim($_POST['name']));
				$num = count($parts);
				if ($num > 1) {
					$lastname = array_pop($parts);
				} else {
					$lastname = 'NA';
				}
				$firstname = implode(" ", $parts);
				//return array($firstname, $lastname);

				$_POST['given_name'] = $firstname;
				$_POST['family_name'] = $lastname;

				// APP
				$_POST['first_name'] = $firstname;
				$_POST['last_name'] = $lastname;

				$_POST['square_id'] = $this->makeCustID();

				// VERIFICATION CODE
				$_POST['ver_code'] = $this->makeVercode();
				// OLD sha1("ChattrBoXX-" . time() . $_POST['email']);

				// 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'];
				}

				$_POST['customer_ip'] = $user_ip;

				$_POST['ref'] = $_POST['refcode']; // ref is primarily used by app, so this copies refcode to ref also
//				echo "<pre>";
//				print_r($_POST);
//				exit;
				//$authsqModel->register($_POST);

				//$user_slug = preg_replace('/[^A-Za-z0-9\-\(\) ]/', '', $_POST['name']);
				
				$user_id = $authsqModel->register($_POST);
				if(!empty($user_id)){
					// increment total users
					$totalMembers = $authsqModel->getTotalUsers();
					if ($totalMembers) {
						$authsqModel->increaseUsers($totalMembers);
					}
				}
				$new_user = $squareuserModel->getUser(['id' => $user_id]);

				$ver_link = "https://base.basepages.com/auth/verify?v=" . $new_user['ver_code'];

				if ($user_id) {
					// SEND VERIFICATION EMAILS
					// Send Email - Always set content-type when sending HTML email
					$headers = "MIME-Version: 1.0" . "\r\n";
					$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
					$headers .= 'From: YourBrand <contact@base.basepages.com>' . "\r\n";
					$headers .= 'Reply-To: YourBrand <contact@base.basepages.com>';

					$email_recipient = $new_user['email'];
					$email_title = "YourBrand Email Verification";

					// HTML FORMATTED MESSAGE EXAMPLE GSIVSpw (ver_code - silly)
					$email_body= "<div style='max-width:580px; margin:0 auto; background:#fff; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; overflow:hidden; font-family:Helvetica,Verdana,sans-serif; padding:0; border:10px solid #eee;'>
				<div style='width:100%; max-height:150px; overflow:hidden; padding:0; margin:0 auto;'>
					<center><img src='https://base.basepages.com/static/system/email_hdr_img.jpg'
					style='width:100%; display:block; background-size:cover; object-fit:cover' /></center>
				</div>
				<div class='clear'></div>
				<div style='border-bottom:2px solid #eee; margin:0 auto; max-width:60%;'></div>
				<div style='padding:15px; background:#fff; text-align:left;'>
					Hello,
					<br /><br />
					Please click the link to verify your email, which also activates your 
					YourBrand Account:
					<br /><br />
					$ver_link
					<br /><br />
					Thank you,
					<br /><br />
					- Tech Support
					<br /><br />
				</div>
				<div class='clear'></div>
				</div>";

					@mail($email_recipient, $email_title, $email_body, $headers,'-fcontact@base.basepages.com');

					$notifSent = 1;

				} // END OF IF USER			

				//$authsqModel->square_login($_POST['email'], $_POST['password']);
				$authsqModel->square_login($_POST['email'], $_POST['password'], isset($_POST['remember']));
				//header('Location: /auth/register?reg_ok');
				header('Location: /membership');
				exit;
				// is_verified_phone, verified_date, is_approved = 0, is_activated = 1, ver_code, emailver
				// all unused: reset_code, pin_code, recovery_code
				// social_id = 10% Club | is_sub means submitted for review
			} else { // END OF CHECK TOKEN 
				echo "Token error...";
			} 
		} // END OF IF POST 
		
		if (isset($_GET['clear'])) {
			$_SESSION['ref'] = '';
			unset($_SESSION['ref']);
			header("Location: /auth/join");
			exit;
		}
		
		if (isset($_GET['clearref'])) {
			$_COOKIE['ref'] = '';
			unset($_COOKIE['ref']);
			$_SESSION['ref'] = '';
			unset($_SESSION['ref']);
			setcookie('ref', '', time() - 3600, '/'); // empty value and old timestamp
			header('Location: /auth/join');
			exit();
		}
        
        // DETECT IF THE GROUP ID IS IN A GET PARAMETER IN THE LINK
//		if (isset($_GET['grp'])) {
//			//echo "Group detection works...";
//			$group_info = $groupsModel->getGroup($_GET['grp']);
//		}
        require 'views/auth/join.tpl.php';
    }    
	
	function parse_name(){

		$full_name = "Movement & Sound Dance LLC";
		//$full_name = "Vernon Hills Gymnastics";
		$parts = explode(" ", $full_name);

		if (count($parts) > 2) {
			$last = array_pop($parts);
			$first= implode(" ", $parts);
		}
		//print_r($first . " " . $last);
		//exit;
	}
	
    function forgot() {
        $authsqModel = new authsqModel();

        if ($_POST) {
            if (isset($_POST['email'])) {
                $u = $authsqModel->preparePasswordReset($_POST['email']);

                if (false === $u) {
                    // wrong email address provided.
                    header("Location: /auth/forgot?msg=" . urlencode("No account is linked to that email address."));
                    exit;
                } 

                $reset_link = get('siteroot') . 'auth/forgot/' . $u['reset_code'];
                //require('views/emails/forgotPwd.eml.php');
                //mail($u['email'], $subject, $body);

						// Send Email - Always set content-type when sending HTML email
						$headers = "MIME-Version: 1.0" . "\r\n";
						$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
						// .'Content-type: text/html; charset=utf-8' . "\r\n"

						// More headers
						$headers .= 'From: YourBrand <contact@base.basepages.com>' . "\r\n";
						$headers .= 'Reply-To: YourBrand <contact@base.basepages.com>';
						$headers .= 'Cc: thinappdev@gmail.com' . "\r\n";
						
						$email_recipient = $u['email'];		
						//print_r($email_recipient);
						//exit;	
						$email_title = "YourBrand Password Reset";	
						$email_body= "<div style='max-width:580px; margin:0 auto; background:#fff; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; overflow:hidden; font-family:Helvetica,Verdana,sans-serif; padding:0; border:10px solid #eee;'>
				<div style='width:100%; max-height:150px; overflow:hidden; padding:0; margin:0 auto;'>
					<center><img src='https://base.basepages.com/static/system/email_hdr_img.jpg'
					style='width:100%; display:block; background-size:cover; object-fit:cover' /></center>
				</div>
				<div class='clear'></div>
				<div style='border-bottom:2px solid #eee; margin:0 auto; max-width:60%;'></div>
				<div style='padding:15px; background:#fff; text-align:left;'>
					Hello,
					<br /><br />
					If
						you recently requested a password reset, please click the link below:
					<br /><br />
					$reset_link
					<br /><br />
					Thank you,
					<br /><br />
					- Tech Support
					<br /><br />
				</div>
				<div class='clear'></div>
				</div>";
										
						@mail($email_recipient, $email_title, $email_body, $headers,'-fcontact@base.basepages.com');

                		$notifSent = 1;
                		
                		//////////////////////////////////////////////////////////
						$user_phone = preparePhone($u['phone']);
						if ($user_phone != '') {
							require "3rdparty/twilio-php-master/Services/Twilio.php";

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

							$client = new Services_Twilio($AccountSid, $AuthToken);
							try {
								$message = $client->account->messages->create(array(
								"From" => "312-878-9582",
								"To" => $user_phone,
								"Body" => "Click the link to reset your YourBrand Password: " . $reset_link,
								));
							} catch (\Exception $e) {
								//return $e->getMessage();
							}
						}
                		
            } elseif (isset($_POST['password'])) {
                if ($authsqModel->resetPassword($_POST['password'], $_POST['code'])) {
                    header("Location: " . get('siteroot') . 'auth/login?msg=' . urlencode("Your password has been updated. You can log in..."));
                } else {
					header("Location: " . get('siteroot') . 'auth/forgot?msg=' . urlencode("Oooops. Something went wrong and your password reset failed."));
                    //echo "Failed to reset pwd";
                }
            }
        }
        if (isset($this->registry->args[2])) {
            $code = $this->registry->args[2];
            if ($authsqModel->checkCode($code)) {
                $codeCorrect = 1;
            } 
        }
        require 'views/auth/forgot.tpl.php';
    }
    
    function validatePC(){
        $refcode = $_POST['c'];
        
        if(!isset($_POST['c'])){
        	$refcode = 'you@22';
        }
        //print_r($refcode);
        //die;
		if (isset($refcode) && $refcode !="") {
			$db = Mysql::getInstance();
			$rid = $db->where("refcode = ?", $refcode)
			->select_one("users", 'id');
			//        print_r($rid);
			//        die;

			if (empty($rid))
				exit;

			echo $rid['id'];
			exit;			
		} else {
			echo 0;
		}

    }	 
    
    // When a user tries to get their Device ID sent to them via email/text
    function validateTheEmail(){
        $refcode = $_POST['c'];
        //print_r($refcode);
        //die;
		if (isset($refcode) && $refcode !="") {
			$db = Mysql::getInstance();
			$rid = $db->where("email = ?", $refcode)
			->select_one("users"); // was id
			//        print_r($rid);
			//        die;

			if (empty($rid)) {
				echo "Hmmm we don't seem to have a match for that.";
				exit;
			} elseif (empty($rid['user_push_id'])) {
				echo "Hmmm. We found your Device ID, but Push Notifications don't appear to be active on your Account. Please see FAQ for more info.";
				exit;
			} else {
				// FOUND A MATCHING EMAIL AND USER_PUSH_ID
				//echo 1;
				
				$push_link = "https://base.basepages.com/api/push/guest_push.php?udid=" . $rid['device_id'];
				
				// Send Email - Always set content-type when sending HTML email
				$headers = "MIME-Version: 1.0" . "\r\n";
				$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
				$headers .= 'From: YourBrand <contact@base.basepages.com>' . "\r\n";
				$headers .= 'Reply-To: YourBrand <contact@base.basepages.com>';
				
				$email_recipient = $rid['email'];		
				$email_title = "YourBrand Device ID";					
				$email_body = "<img src='https://base.basepages.com/static/images/email_header.jpg' alt='YourBrand' style='width:100%; height:auto;' />
				<br />
				Hello,
				<br /><br />
				You recently requested your Device ID. To send yourself a push notification, click the link below: 
				<br /><br />
				$push_link
				<br /><br />
				Thank you,
				<br /><br />
				- Tech Support";				

				@mail($email_recipient, $email_title, $email_body, $headers,'-fcontact@base.basepages.com');

        		$notifSent = 1;
        		
        		//////////////////////////////////////////////////////////
				$user_phone = preparePhone($rid['phone']);
				if ($user_phone != '') {
					require "3rdparty/twilio-php-master/Services/Twilio.php";

					$AccountSid = "ACc33ee9aa71e9a841111c0f6ef976af61";
					$AuthToken = "774b5173cc5c1ba2b61ee20769888fa1";

					$client = new Services_Twilio($AccountSid, $AuthToken);
					try {
						$message = $client->account->messages->create(array(
						"From" => "312-878-9582",
						"To" => $user_phone,
						"Body" => "To send yourself a push notification, first click this link: " . $push_link,
						));
					} catch (\Exception $e) {
						//return $e->getMessage();
					}
				}
				exit;
			}
			//echo $rid['device_id']; // was id
			//echo 1; // was id
			//exit;			
		} else {
			echo 0;
		}

    }	 
    
    function checkTheEmail(){
		//$email = mysql_real_escape_string($_POST['email']); 
        $email = stripslashes(htmlentities($_POST['email'])); 
		
		if (!empty($email)) {
			$db = Mysql::getInstance();
			$subemail = $db->where("email = ?", $email)
							  ->select_one("users", 'email');

			if($subemail > 0) {
				echo 1;
			} else {
				echo 0;
			}
		} else {
				echo 1;
		}
    }	  
    
    // Let's verify and validate the User's phone number AND carrier
    function validatePhone(){
		$phone = stripslashes(htmlentities($_POST['phone']));
		$carrier = $_POST['carrier'];
		
		//$clean_phonenumber = strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/','', $phone));
		
		$clean_phonenumber = preg_replace("/[^a-zA-Z0-9]+/", "", $phone);
		
//		echo $clean_phonenumber;
//		exit;
		
		// MAPPING OF THE CARRIERS TO EMAIL EXTENSION
		if ($carrier == "ATT") { $carrier_extension = "txt.att.net";
		} elseif($carrier == "Sprint"){ $carrier_extension = "messaging.sprintpcs.com";
		} elseif($carrier == "Verizon"){ $carrier_extension = "vtext.com";
		} elseif($carrier == "T-Mobile"){ $carrier_extension = "tmomail.net";
		} elseif($carrier == "USCellular"){ $carrier_extension = "email.uscc.net";
		} elseif($carrier == "BoostMobile"){ $carrier_extension = "sms.myboostmobile.com";
		} elseif($carrier == "C-Spire"){ $carrier_extension = "cspire1.com";
		} elseif($carrier == "ConsumerCellular"){ $carrier_extension = "mailmymobile.net";
		} elseif($carrier == "Cricket"){ $carrier_extension = "sms.cricketwireless.net";
		} elseif($carrier == "GoogleFi"){ $carrier_extension = "msg.fi.google.com";
		} elseif($carrier == "H2OWireless"){ $carrier_extension = "txt.att.net";
		} elseif($carrier == "MetrobyT-Mobile"){ $carrier_extension = "mymetropcs.com";
		} elseif($carrier == "MintMobile"){ $carrier_extension = "mailmymobile.net";
		} elseif($carrier == "PagePlus"){ $carrier_extension = "vtext.com";
		} elseif($carrier == "RedPocket"){ $carrier_extension = "txt.att.net";
		} elseif($carrier == "RepublicWireless"){ $carrier_extension = "text.republicwireless.com";
		} elseif($carrier == "SimpleMobile"){ $carrier_extension = "smtext.com";
		} elseif($carrier == "Ting"){ $carrier_extension = "number@message.ting.com";
		} elseif($carrier == "Tracfone"){ $carrier_extension = "mmst5.tracfone.com";
		} elseif($carrier == "UltraMobile"){ $carrier_extension = "mailmymobile.net";
		} elseif($carrier == "USMobile"){ $carrier_extension = "vtext.com";
		} elseif($carrier == "VirginMobile"){ $carrier_extension = "vmobl.com";
		} elseif($carrier == "Visible"){ $carrier_extension = "vtext.com";
		} elseif($carrier == "XfinityMobile"){ $carrier_extension = "vtext.com";
		} else {
			//echo "Something went wrong... Please contact Tech Support at support@chattrboxx.com.";
		}
		
		$userphone = $clean_phonenumber . '@' . $carrier_extension;
		//echo $userphone;
		// CHAD
		// $userphone = "8157612950@vtext.com";
		/*
		
		Red Pocket Red Pocket uses AT&T or T-Mobile (for GSM SIMs) & Verizon for CDMA
		
		Ting
		number@message.ting.com (SMS for CDMA)
		number@tmomail.net (SMS for GSM)

		AT&T: number@txt.att.net (SMS), number@mms.att.net (MMS)
		Sprint: number@messaging.sprintpcs.com (SMS), number@pm.sprint.com (MMS)
		T-Mobile: number@tmomail.net (SMS & MMS)
		Verizon: number@vtext.com (SMS), number@vzwpix.com (MMS)
		U.S. Cellular: number@email.uscc.net (SMS), number@mms.uscc.net (MMS)
		
		Boost Mobile: number@sms.myboostmobile.com (SMS), number@myboostmobile.com (MMS)
		C-Spire: number@cspire1.com
		Consumer Cellular: number@mailmymobile.net
		Cricket: number@sms.cricketwireless.net (SMS), number@mms.cricketwireless.net (MMS)
		Google Fi (Project Fi): number@msg.fi.google.com (SMS & MMS)
		H2O Wireless: number@txt.att.net (SMS), number@mms.att.net (MMS)
		Metro by T-Mobile: number@mymetropcs.com (SMS & MMS)
		Mint Mobile: number@mailmymobile.net (SMS)
		Page Plus: number@vtext.com (SMS), number@mypixmessages.com (MMS)
		Red Pocket: Red Pocket uses AT&T or T-Mobile (for GSM SIMs) & Verizon for CDMA. See info. for those carriers.
		Republic Wireless: number@text.republicwireless.com (SMS)
		Simple Mobile: number@smtext.com (SMS)
		Ting: number@message.ting.com (SMS for CDMA), number@tmomail.net (SMS for GSM)
		Tracfone: number@mmst5.tracfone.com (MMS)
		Ultra Mobile: number@mailmymobile.net
		U.S. Mobile: number@vtext.com (SMS), number@mypixmessages.com (MMS)
		Virgin Mobile: number@vmobl.com (SMS), number@vmpix.com (MMS)
		Visible: number@vtext.com (SMS), number@vzwpix.com (MMS)
		Xfinity Mobile: number@vtext.com (SMS), number@mypixmessages.com (MMS)
		*/
		
		// JIMMY 
		//$userphone = "8474768171@tmomail.net";
		
		//echo 1;
        
//        if(!isset($_POST['c'])){
//        	$refcode = 'you@22';
//        }
        //print_r($refcode);
        //die;
        
        // Let's send the email/text!
		if (isset($phone) && $phone !="") {
			$link = "https://base.basepages.com/profile/verify?c=" . $_SESSION['user']['ver_code'];
			// Send Email - Always set content-type when sending HTML email
			$headers = "MIME-Version: 1.0" . "\r\n";
			$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
			$headers .= 'From: YourBrand <contact@base.basepages.com>' . "\r\n";
			$headers .= 'Reply-To: YourBrand <contact@base.basepages.com>';
			
			$email_recipient = $userphone;		
			//$email_title = "Phone Verification";					
			$email_body = "Click to verify your phone #: " . $link;				

			@mail($email_recipient, $email_title, $email_body, $headers,'-fcontact@base.basepages.com');

			//$notifSent = 1;
			echo 1;	
			exit;
			//echo $rid['device_id']; // was id
			//echo 1; // was id
			//exit;		
		} else {
			echo 0;
		}
    }	   
	
	function addtoGroup($group_id, $user_id){
		$groupsModel = new groupsModel();	
		$groupsModel->addtoGroup($group_id, $user_id);
    }  
    
	function addtoAllGroup($referrer_id, $user_id){
		$groupsModel = new groupsModel();	
		$groupsModel->addtoAllGroup($referrer_id, $user_id);
    }            
    
	function keypad(){
		if ($_POST) {
			$authsqModel = new authsqModel();

			//$red irect_to = get('siteroot');
			//$redirect_to = get('siteroot') . 'home/';
			$redirect_to = get('siteroot') . '';
			if (!empty($_POST['redirect_me']) && $this->validURI($_POST['redirect_me']))
				$redirect_to = rtrim(get('siteroot'), "/") . "/" . ltrim($_POST['redirect_me'], "/");

			$loginnow = $authsqModel->pincode_login($_POST['pin_code']); 
				//print_r($loginnow);
				if ($loginnow == 0) {
					$msg = "Wrong PIN Code";
					require 'views/auth/keypad.tpl.php';					
				} else if($loginnow == 1){
					if ($_SESSION['user']['is_admin']==1) {
						header("Location: /admin/dash");
						exit;
					} else if ($_SESSION['user']['usertype']=='Team') {
						header("Location: /admin/dash");
						exit;						
					} else {
						//header("Location: " . $redirect_to);
						header("Location: /auth/keypad?msg=Not Authorized");
						exit;
					}					
				} else {
					$msg = "Please enter a valid 4-digit PIN Code to login.";
					require 'views/auth/keypad.tpl.php';					
				}
		}

		// END OF GET
		require 'views/auth/keypad.tpl.php';
	}    
	
	function testRef(){
		// test to see if the getRefID is returning a referral ID
//		$refcode = "team";
//		$this->getRefID($refcode);


		$groupsModel = new groupsModel();	
		
		// See if the all function is working...
//		$refcode = "team";
//		if (isset($refcode)) {
//			$ref_id = $this->getRefID($refcode);
//			if (isset($ref_id)) {
//				$groupsModel->addtoAllGroup($ref_id, $user_id);
//			}
//		}  
		
		$group_id = 65;
		$owner_id = $groupsModel->getGroupOwnerID($group_id);
		
		print_r($owner_id);
	}   

	function getRefID($refcode){
		//$ref = $_POST['ref'];
		//$ref = mysqli_real_escape_string($this->conn,$_POST['ref']);
		$db = Mysql::getInstance();
		$ref = stripslashes(htmlentities($refcode));
		$refid = $db->where("refcode = ?", $ref) // we also have ref in the table in the last column
		->select_one("users", 'id');

		if ($refid > 0) {
			return $refid['id']; // Not Available
		}
	}	
	
	function getRefName($refcode){
		//$ref = $_POST['ref'];
		//$ref = mysqli_real_escape_string($this->conn,$_POST['ref']);
		$db = Mysql::getInstance();
		$ref = stripslashes(htmlentities($refcode));
		$refname = $db->where("refcode = ?", $ref) // we also have ref in the table in the last column
		->select_one("users", 'name');

		if (!empty($refname)) {
			return $refname['name']; // Not Available
		}
	}	
	
	function checkRef(){
		//$ref = $_POST['ref'];
		//$ref = mysqli_real_escape_string($this->conn,$_POST['ref']);
		$db = Mysql::getInstance();
		$ref = stripslashes(htmlentities($_POST['ref']));
		$refid = $db->where("refcode = ?", $ref) // we also have ref in the table in the last column
		->select_one("users", 'id');

		if ($refid > 0) {
			echo 0; // Not Available
		} else {
			echo 1; // Available
		}
	}	  	
	
    function checkEmail(){
		//$email = mysql_real_escape_string($_POST['email']); 
        $email = stripslashes(htmlentities($_POST['email'])); 
		// $interestedin = stripslashes(htmlentities($_POST['interestedin']));
		// to check emails BY interested in (which is like a topic or group)
		// need to pass the interested in input into a jquery variable and into the ajax
		// in the subscribers module (in the views/includes folder)
		
		if (!empty($email)) {
			$db = Mysql::getInstance();
			$subemail = $db->where("email = ?", $email)
						   //->where("interestedin=?", $interestedin)
						   ->select_one("subscribers", 'email');

			if($subemail > 0) {
				echo 1;
			} else {
				echo 0;
			}
		} else {
				echo 1;
		}
    }	
	
	// https://yourbrand.com/auth/verify?v=GSIVSpw
    function verify(){
		// https://yourbrand.com/auth/verify?c=12er2vef
//		echo "test";
//		exit;
		
		$code = $_GET['c']; // phone number 
		$verification =  $_GET['v']; // email
		
//		print_r($verification);
//		exit;
		
		if (isset($_GET['c'])) {

			$db = Mysql::getInstance();
			$user_id = $db->where("ver_code = ?", $code)
			->select_one("users", 'id');

			//		print_r($user_id);
			//		exit;

			if (empty($user_id))
				return false;

			$db->where("id = ?", $user_id)
			->update("users", [
				'is_verified_phone' => 1,
				'verified_date'  => date("Y-m-d H:i:s")]);

			//	    $this->db->where("id = ?", $user_id);
			//	    $this->db->update("users", [
			//	        'is_verified_phone'  => 1,
			//	        'verified_date' => date("Y-m-d H:i:s")]);

			//echo "yes!";
			// https://chattrboxx.com/auth/login?msg=Phone+Number+Verified!+You+can+log+in...
			header("Location: /auth/login?msg=Phone+Number+Verified!+You+can+log+in..."); 
			exit;
			//require 'views/content_pages/phoneverified.tpl.php';
			//include ('views/profile/verified.tpl.php');
			//https://chattrboxx.com/phoneverified
			//return $user_id;
		}
		
		// EMAIL
		if (isset($_GET['v'])) {

			$db = Mysql::getInstance();
			$user_id = $db->where("ver_code = ?", $verification)
			->select_one("users", 'id');

//			print_r($user_id);
//			exit;

			if (empty($user_id))
				return false;

			$db->where("id = ?", $user_id)
			->update("users", [
				'emailver' => 1,
				'is_activated'  => 1
			]);

			//	    $this->db->where("id = ?", $user_id);
			//	    $this->db->update("users", [
			//	        'is_verified_phone'  => 1,
			//	        'verified_date' => date("Y-m-d H:i:s")]);

			//echo "yes!";

			require 'views/content_pages/emailverified.tpl.php';
			//include ('views/profile/verified.tpl.php');
			//https://chattrboxx.com/phoneverified
			//return $user_id;
		}		
	}         
    
    // SUBSCRIBE MODULE - LOCATED IN /views/includes/subscriber.tpl.php and /controllers/index.php
	function subscribe() {
			
		if ($_POST) {	
			
			//$subemail = !empty($_POST['email']) ? $_POST['email'] : false;
			
			$authModel = new authsqModel();
			$authModel->subscribe($_POST);		    	

			$subscriber_email = stripslashes(htmlentities($_POST['email']));  
			$db = Mysql::getInstance();
			$subs = $db->where("email = ?", $subscriber_email)
							->limit(1)
							->select_one("subscribers");
							 //$subscriber = $db->select_one("subscribers");
							 
			if (!empty($subs)) 
			$code = $subs['code'];
				
			$headers  = 'From: YourBrand <contact@basepages.com>' . "\r\n";
			$headers .= 'Reply-To: contact@basepages.com' . "\r\n"; 
			$headers .= "MIME-Version: 1.0\r\n";
			$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";	 				
				
			$msg= "<center><img src='https://base.basepages.com/static/system/email_hdr.jpg' style='width:100%;' /></center>
                    <div style='text-align:left;'>
                    <br /><br />
					Hello. You have successfully reserved a spot in YourBrand.
                    <br /><br />
                    We will be in touch once we get closer to launching.
                    <br /><br />
                    Thank you,<br />
					- Tech Support<br />
                    </div>"; 			
			//if(!empty($subemail)){
				@mail($subscriber_email, "You're reserved! Thanks!", $msg, $headers,"-fcontact@basepages.com");    
			//} else {
			//   @mail("demo@yourbrand.com", "Your Code!", $msg, $headers,"-fcontact@yourbrand.com");
			//}
						
			
			//header('Location: /vip-success');
			exit;
		}		
		
		//@mail("demo@yourbrand.com", "Your Email Title", "You have a new Subscriber!", "From: YourBrand <contact@yourbrand.com>");
	
        //$redirect_url  = "/profile/myDashboard";
        //if (!empty($_GET['referer_url']))
        //    $redirect_url = $_GET['referer_url'];
		
		//require 'views/content_pages/reserved.tpl.php';
    }    
    
    function checkCount(){

        $db = Mysql::getInstance();
        $c = $db->select('subscribers', 'COUNT(*) AS c')[0]['c'];

        if (empty($c))
            exit;

        //echo $rid['id']; // this was the original and was working fine for referrer's ID
		//echo json_encode(array("rid" => $rid['id'], "referrer" => $rid['name'])); // this was the 2nd option, which I couldn't parse
		echo $c;
		//$json = new Services_JSON(); // first part of 3rd option, but I don't think I need it
		//echo $json->encode("{a:1,b:2}");
        exit;
    }	    
    
//	<br /><br />
//	Your unique Reservation Code is: <strong>" . $code . "</strong>.
//	<br /><br />

    function logout() {
        unset($_SESSION['loggedin']);
        unset($_SESSION['user_id']);
        unset($_SESSION['user']);

        header("Location: /");
        // $this->index();
    }
    
	function logout_pincode()
	{
		unset($_SESSION['loggedin']);
		unset($_SESSION['user_id']);
		unset($_SESSION['user']);

		header("Location: /auth/keypad");
		// $this->index();
	}    
	
	function getLast(){
		$authsqModel = new authsqModel();
		$lastBatch = $authsqModel->getLastBatch();
		print_r($lastBatch);	
	}
	
	function getLastPos(){
		$authsqModel = new authsqModel();
		$lastPos = $authsqModel->getLastPosition();
		print_r($lastPos);	
	}
	
	// https://base.basepages.com/auth/view
	function view(){
		$authsqModel = new authsqModel();
		//$check = $authsqModel->testfunction();
		
		$check = $authsqModel->checkifweshouldpickaWinner();
		print_r($check);
	}
	
//	function randomNum(){
//		$randomIndex = mt_rand(1, 10);
//		echo $randomIndex;
//	}
//	function test(){
//		$params = session_get_cookie_params();
//		print_r($params);
//		Array ( [lifetime] => 0 [path] => / [domain] => [secure] => [httponly] => )
//	}
}
?>