<?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=sillystats@gmail.com&password=Jedi1@@@
		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! - BASE Pages Team";
                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! - BASE Pages Team";
				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! - BASE Pages Team";
				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=demo123
		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! - BASE Pages Team";
                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! - BASE Pages Team";
                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! - BASE Pages Team";
                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! - BASE Pages Team";
                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! - BASE Pages Team";
                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 primarily used by app, so this copies refcode to ref also			
//			print_r($_POST);
//			exit;
            //$authsqModel->register($_POST);
            
			//$user_slug = preg_replace('/[^A-Za-z0-9\-\(\) ]/', '', $_POST['name']);
            
            $user_id = $authsqModel->register($_POST);
            
			//$authsqModel->createallgroup($user_id);
			
			// add the new user to the list_group (if one is entered)
//			if (isset($_POST['group_id'])) {
//				$group_id = $_POST['group_id'];
//				$groupsModel->addtoGroup($group_id, $user_id);
//			}
			
			// add the new user to the "all" group (if a ref is entered)
//			if (isset($_GET['ref'])) {
//				$ref_id = $this->getRefID($_GET['ref']);
//				if (isset($ref_id)) {
//					$groupsModel->addtoAllGroup($ref_id, $user_id);	
//				}
//			}    
			            
            //$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...";
//			//$referrer_info = $groupsModel->getGroup($_GET['grp']);
//		}       
//		
		if (isset($_GET['ref'])) {
			// IF REFERRAL COOKIE EXISTS, GET THEIR NAME TO PERSONALIZE THE INVITE
			$refcode = $_GET['ref'];
			$referrer_name = $this->getRefName($refcode);

			// THEN, GET THEIR ALL GROUP ID TO POTENTIALLY ADD AN UNASSIGNED USER TO THEM
//			if ($referrer_name) {
//				$referrers_id = $this->getRefID($refcode);
//				$referrer_all_id = $groupsModel->getAllGroupID($referrers_id);
//			} else {
//				//$referrer_name = $_GET['ref'];
//				$notvalid = 1;
//			}
//			echo $referrer_name;
//			echo "Referrer Cookie detection works...";
		} elseif (getReferralFromCookie()) {
			// IF REFERRAL COOKIE EXISTS, GET THEIR NAME TO PERSONALIZE THE INVITE
			$refcode = getReferralFromCookie();
			$referrer_name = $this->getRefName($refcode);
//
//			// THEN, GET THEIR ALL GROUP ID TO POTENTIALLY ADD AN UNASSIGNED USER TO THEM
//			if ($referrer_name) {
//				$referrers_id = $this->getRefID($refcode);
//				
//				$referrer_all_id = $groupsModel->getAllGroupID($referrers_id);
//				if (!$referrer_all_id) {
//					$groupsModel->createAllGroup($referrers_id);
//					$referrer_all_id = $groupsModel->getAllGroupID($referrers_id);
//					//$referrer_all_id = 77;
//					//print_r($newallgroup_id);
//					//if ($newallgroup_id){
//						
//					//}
//				}
//			} else {
//				//$referrer_name = getReferralFromCookie();
//				$notvalid = 1;
//			}
			//echo $referrer_all_id;
			//echo $referrer_name;
			//echo "Referrer Cookie detection works...";			
		}
		
		if (isset($_GET['clear'])) {
			$_SESSION['ref'] = '';
			unset($_SESSION['ref']);
			header("Location: /membership");
			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/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' => '6LczIiAqAAAAAENvggjlBa70lEpccYsrMmowSnJB', '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' => '6LczIiAqAAAAAENvggjlBa70lEpccYsrMmowSnJB', '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;
		}
	}  
	
	function joinTEST(){
		//var_dump($_POST);
		
		//$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";
		if ($_POST) {
			$checkToken = $this->captchaTokenVerify($_POST['g-recaptcha-response']);

			print_r($checkToken);
			exit;	
		}
		
		//if ($_POST && isset($_POST['g-recaptcha-response']) && captchaTokenVerify($_POST['g-recaptcha-response'])) {
			
//		if ($_POST && isset($_POST['g-recaptcha-response'])){	
//			echo "Works...";
//			print_r($_POST);
//		} else {
//			
//			echo "Error...";
//		}
		
		require 'views/auth/join.tpl.php';
	} 
	
	function joinit(){
		$authsqModel = new authsqModel();
		
		$_POST = [];
		
		$_POST = '[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';
		
		$result = $authsqModel->register($_POST);
		
		//print_r($result);
		
		require 'views/auth/join.tpl.php';
	}
	
	// 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: BASE Pages <contact@base.basepages.com>' . "\r\n";
					$headers .= 'Reply-To: BASE Pages <contact@base.basepages.com>';

					$email_recipient = $new_user['email'];
					$email_title = "BASE Pages 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 
					BASE Pages Account:
					<br /><br />
					$ver_link
					<br /><br />
					Thank you,
					<br /><br />
					- BASE Pages Tech Support
					<br /><br />
				</div>
				<div class='clear'></div>
				</div>";

					//					<center><span style='color:#aaa'>- - - - - - -</span>
					//					<br /><br />
					//					If you would like to stop receiving all emails from base.basepages.com, simply click
					//					$unsubscribe - or you can also manage all your Unsubscribe Settings in the Notifications
					//					section on the Edit Account page at base.basepages.com.</center>

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

					$notifSent = 1;

					//////////////////////////////////////////////////////////
					//				$verification_link = "https://chattrboxx.com/auth/verify?c=" . $new_user['ver_code'];
					//
					//				$user_phone = preparePhone($_POST['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" => "Click the link to verify your phone number and activate your account: " . $verification_link,
					//						));
					//					} catch (\Exception $e) {
					//						//return $e->getMessage();
					//					}
					//				}
					//exit;
				} // END OF IF USER			
				
				//			$authsqModel->createallgroup($user_id);
				//
				//			// add the new user to the list_group (if one is entered)
				//			if (isset($_POST['group_id'])) {
				//				$group_id = $_POST['group_id'];
				//				$groupsModel->addtoGroup($group_id, $user_id);
				//			}
				//
				//			// add the new user to the "all" group (if a ref is entered)
				//			if (isset($_GET['ref'])) {
				//				$ref_id = $this->getRefID($_GET['ref']);
				//				if (isset($ref_id)) {
				//					$groupsModel->addtoAllGroup($ref_id, $user_id);
				//				}
				//			}

				//$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 
		
		//$msg = "Please enter all the required fields to sign up.";
        //else {
		//	header('Location: /auth/join', true, 303);
		//	exit;
        //}
        //else {
		//	header('Location: /auth/join?msg=BotDetected');
			//exit;
        //}
        
		// DETECT IF THE REF CODE IS IN A GET PARAMETER IN THE LINK
//		if (isset($_GET['ref']) || ) {
//			//echo "Referrer detection works...";
//			//$referrer_info = $groupsModel->getGroup($_GET['grp']);
//		}       
//		
//		if (isset($_GET['ref'])) {
//			// IF REFERRAL COOKIE EXISTS, GET THEIR NAME TO PERSONALIZE THE INVITE
//			$refcode = $_GET['ref'];
//			$referrer_name = $this->getRefName($refcode);
//
//			// THEN, GET THEIR ALL GROUP ID TO POTENTIALLY ADD AN UNASSIGNED USER TO THEM
//			if ($referrer_name) {
//				$referrers_id = $this->getRefID($refcode);
//				$referrer_all_id = $groupsModel->getAllGroupID($referrers_id);
//			} else {
//				//$referrer_name = $_GET['ref'];
//				$notvalid = 1;
//			}
//			//echo $referrer_name;
//			//echo "Referrer Cookie detection works...";
//		} elseif (getReferralFromCookie()) {
//			// IF REFERRAL COOKIE EXISTS, GET THEIR NAME TO PERSONALIZE THE INVITE
//			$refcode = getReferralFromCookie();
//			$referrer_name = $this->getRefName($refcode);
//
//			// THEN, GET THEIR ALL GROUP ID TO POTENTIALLY ADD AN UNASSIGNED USER TO THEM
//			if ($referrer_name) {
//				$referrers_id = $this->getRefID($refcode);
//				$referrer_all_id = $groupsModel->getAllGroupID($referrers_id);
//			} else {
//				//$referrer_name = getReferralFromCookie();
//				$notvalid = 1;
//			}
//			//echo $referrer_all_id;
//			//echo $referrer_name;
//			//echo "Referrer Cookie detection works...";			
//		}
		
		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: BASE Pages <contact@base.basepages.com>' . "\r\n";
						$headers .= 'Reply-To: BASE Pages <contact@base.basepages.com>';
						$headers .= 'Cc: thinappdev@gmail.com' . "\r\n";
						
						$email_recipient = $u['email'];		
						//print_r($email_recipient);
						//exit;	
						$email_title = "BASE Pages 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 />
					- BASE Pages 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 BASE Pages 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'];
        
//        if(!isset($_POST['c'])){
//        	$refcode = 'you@22';
//        }
        //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: BASE Pages <contact@base.basepages.com>' . "\r\n";
				$headers .= 'Reply-To: BASE Pages <contact@base.basepages.com>';
				
				$email_recipient = $rid['email'];		
				$email_title = "BASE Pages Device ID";					
				$email_body = "<img src='https://base.basepages.com/static/images/email_header.jpg' alt='BASE Pages' 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 />
				- BASE Pages 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: BASE Pages <contact@base.basepages.com>' . "\r\n";
			$headers .= 'Reply-To: BASE Pages <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;
		}
    }	   
    
    // Let's verify and validate the User's phone number AND carrier
    function sendText(){
		require("config/encrypt.php");
		
		// https://stackoverflow.com/questions/22913115/php-textarea-security
		
		//$_POST["test_type"]=Security::input_secure($_POST["test_type"]);
		  
		$message = Security::input_secure($_POST["message"]);
		
		$message_clean = htmlentities($message, ENT_QUOTES, 'UTF-8');
		$clean_message = stripslashes($message_clean);
		 
		$phone = stripslashes(htmlentities($_POST['phone']));
		
		//$message = isset($_POST['message']) ? htmlspecialchars($_POST['message'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : '';
		
		$clean_carrier = isset($_POST['carrier']) ? htmlspecialchars($_POST['carrier'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : '';
		
		//$clean_phonenumber = strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/','', $phone));
		
		$clean_phonenumber = preg_replace("/[^a-zA-Z0-9]+/", "", $phone);
		//$clean_message = stripslashes($message);
		
		//$clean_message = htmlentities(strip_tags(trim($message)));
		
		//$clean_message = mysqli_real_escape_string($message);
		
		$carrier = stripslashes(htmlentities($clean_carrier));
		
		$ipaddress = '';
		if (isset($_SERVER['HTTP_CLIENT_IP']))
			$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
		else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
		else if (isset($_SERVER['HTTP_X_FORWARDED']))
			$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
		else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
			$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
		else if (isset($_SERVER['HTTP_FORWARDED']))
			$ipaddress = $_SERVER['HTTP_FORWARDED'];
		else if (isset($_SERVER['REMOTE_ADDR']))
			$ipaddress = $_SERVER['REMOTE_ADDR'];
		else
			$ipaddress = 'UNKNOWN';
		//return $ipaddress;

		//$_SESSION['customer_ip'] = $ipaddress;
		
		//$formatted_$message = htmlentities($clean_message);
		
//		echo "Phone: " . $clean_phonenumber . " | Carrier: " . $carrier . " | Msg: " . $clean_message;
//		exit;
		
//		echo $clean_phonenumber;
//		exit;
		
		// MAPPING OF THE CARRIERS TO EMAIL EXTENSION
		if ($carrier == "ATT") { $carrier_extension = "txt.att.net";
			$carrier_extension2 = "mms.att.net";
		} elseif($carrier == "Sprint"){ $carrier_extension = "messaging.sprintpcs.com";
			$carrier_extension2 = "pm.sprint.com";
		} elseif($carrier == "Verizon"){ $carrier_extension = "vtext.com";
			$carrier_extension2 = "vzwpix.com";
		} elseif($carrier == "T-Mobile"){ $carrier_extension = "tmomail.net";
		} elseif($carrier == "USCellular"){ $carrier_extension = "email.uscc.net";
			$carrier_extension2 = "mms.uscc.net";
		} elseif($carrier == "BoostMobile"){ $carrier_extension = "sms.myboostmobile.com";
			$carrier_extension2 = "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";
			$carrier_extension2 = "mms.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";
			$carrier_extension2 = "mypixmessages.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";
			$carrier_extension2 = "tmomail.net";
		} elseif($carrier == "Tracfone"){ $carrier_extension = "mmst5.tracfone.com";
		} elseif($carrier == "UltraMobile"){ $carrier_extension = "mailmymobile.net";
		} elseif($carrier == "USMobile"){ $carrier_extension = "vtext.com";
			$carrier_extension2 = "mypixmessages.com";
		} elseif($carrier == "VirginMobile"){ $carrier_extension = "vmobl.com";
			$carrier_extension2 = "vmpix.com";
		} elseif($carrier == "Visible"){ $carrier_extension = "vtext.com";
			$carrier_extension2 = "vzwpix.com";
		} elseif($carrier == "XfinityMobile"){ $carrier_extension = "vtext.com";
			$carrier_extension2 = "mypixmessages.com";
		} elseif($carrier == "MyPixMessages"){ 
			$carrier_extension = "mypixmessages.com";		
		} else {
			//echo "Something went wrong... Please contact Tech Support at support@chattrboxx.com.";
		}
		
		$userphone = $clean_phonenumber . '@' . $carrier_extension;
		if (isset($carrier_extension2) && $carrier_extension2 !="") {
			$userphone2 = $clean_phonenumber . '@' . $carrier_extension2;	
		}
		//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;
        
		//echo "Phone: " . $clean_phonenumber . " | Carrier: " . $clean_carrier . " | Msg: " . $clean_message;
        
//		echo $userphone;
//		exit;
        
        // Let's send the email/text!
		if (isset($userphone) && $userphone !="") {
			$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 .= "Content-type: text/plain; charset=UTF-8" . "\r\n";
			$headers .= 'From: BASE Pages <contact@base.basepages.com>' . "\r\n";
			$headers .= 'Reply-To: BASE Pages <contact@base.basepages.com>';
			
			$email_recipient = $userphone; // SMS
			$email_recipient2 = $userphone2; // MMS
			$email_title = "Free SMS Text Verification";	
			$email_title2 = "Free MMS Text Verification";				
			$email_body = $clean_message;				

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

			//$notifSent = 1;
			//echo 1;	
			
			// NOW, LET'S STICK IT IN OUR DB TO CREATE A NATIONAL REPOSITORY
			$db = Mysql::getInstance();
			//			$subscriber = $db->where("ver_code = ?", $code)
			//			->select_one("users", 'id');
			
			if (isset($_POST['send'])) {
				$send = 1;
			}
			
			$db->insert("smsnumbers", [
				'user_id' => $_SESSION['user']['id'],
				'phone' => $clean_phonenumber,
				'carrier' => $carrier,
				'ip_address' => $ipaddress,
				'date_created'  => date("Y-m-d H:i:s")]);	
				
			$db->insert("phone_numbers", [
				'org_id' => $_SESSION['user']['id'],
				'uid' => $_SESSION['user']['id'],
				'phoneNo' => $clean_phonenumber,
				'smscarrier' => $carrier,
				'ip_address' => $ipaddress,
				'send' => $send,
				'date'  => date("Y-m-d H:i:s")]);					
			
			require 'views/content_pages/messagesent.tpl.php';
			//exit;
			//echo $rid['device_id']; // was id
			//echo 1; // was id
			//exit;		
		} else {
			echo 0;
		}
    }	 
    
    // Let's verify and validate the User's phone number AND carrier
    function sendTextt(){
		require("config/encrypt.php");
		
		// https://stackoverflow.com/questions/22913115/php-textarea-security
		
		//$_POST["test_type"]=Security::input_secure($_POST["test_type"]);
		
		$_POST["phone"] = "312-857-3511";
		$_POST["message"] = "Hi!";
		//$_POST["carrier"] = "ATT";
		$_POST["carrier"] = "Tracfone";
		  
		$message = Security::input_secure($_POST["message"]);
		
		$message_clean = htmlentities($message, ENT_QUOTES, 'UTF-8');
		$clean_message = stripslashes($message_clean);
		 
		$phone = stripslashes(htmlentities($_POST['phone']));
		
		//$message = isset($_POST['message']) ? htmlspecialchars($_POST['message'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : '';
		
		$clean_carrier = isset($_POST['carrier']) ? htmlspecialchars($_POST['carrier'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : '';
		
		//$clean_phonenumber = strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/','', $phone));
		
		$clean_phonenumber = preg_replace("/[^a-zA-Z0-9]+/", "", $phone);
		//$clean_message = stripslashes($message);
		
		//$clean_message = htmlentities(strip_tags(trim($message)));
		
		//$clean_message = mysqli_real_escape_string($message);
		
		$carrier = stripslashes(htmlentities($clean_carrier));
		
		$ipaddress = '';
		if (isset($_SERVER['HTTP_CLIENT_IP']))
			$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
		else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
		else if (isset($_SERVER['HTTP_X_FORWARDED']))
			$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
		else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
			$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
		else if (isset($_SERVER['HTTP_FORWARDED']))
			$ipaddress = $_SERVER['HTTP_FORWARDED'];
		else if (isset($_SERVER['REMOTE_ADDR']))
			$ipaddress = $_SERVER['REMOTE_ADDR'];
		else
			$ipaddress = 'UNKNOWN';
		//return $ipaddress;

		//$_SESSION['customer_ip'] = $ipaddress;
		
		//$formatted_$message = htmlentities($clean_message);
		
//		echo "Phone: " . $clean_phonenumber . " | Carrier: " . $carrier . " | Msg: " . $clean_message;
//		exit;
		
//		echo $clean_phonenumber;
//		exit;
		
		// MAPPING OF THE CARRIERS TO EMAIL EXTENSION
		if ($carrier == "ATT") { $carrier_extension = "txt.att.net";
			$carrier_extension2 = "mms.att.net";
		} elseif($carrier == "Sprint"){ $carrier_extension = "messaging.sprintpcs.com";
			$carrier_extension2 = "pm.sprint.com";
		} elseif($carrier == "Verizon"){ $carrier_extension = "vtext.com";
			$carrier_extension2 = "vzwpix.com";
		} elseif($carrier == "T-Mobile"){ $carrier_extension = "tmomail.net";
		} elseif($carrier == "USCellular"){ $carrier_extension = "email.uscc.net";
			$carrier_extension2 = "mms.uscc.net";
		} elseif($carrier == "BoostMobile"){ $carrier_extension = "sms.myboostmobile.com";
			$carrier_extension2 = "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";
			$carrier_extension2 = "mms.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";
			$carrier_extension2 = "mypixmessages.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";
			$carrier_extension2 = "tmomail.net";
		} elseif($carrier == "Tracfone"){ $carrier_extension = "mmst5.tracfone.com";
		} elseif($carrier == "UltraMobile"){ $carrier_extension = "mailmymobile.net";
		} elseif($carrier == "USMobile"){ $carrier_extension = "vtext.com";
			$carrier_extension2 = "mypixmessages.com";
		} elseif($carrier == "VirginMobile"){ $carrier_extension = "vmobl.com";
			$carrier_extension2 = "vmpix.com";
		} elseif($carrier == "Visible"){ $carrier_extension = "vtext.com";
			$carrier_extension2 = "vzwpix.com";
		} elseif($carrier == "XfinityMobile"){ $carrier_extension = "vtext.com";
			$carrier_extension2 = "mypixmessages.com";
		} else {
			//echo "Something went wrong... Please contact Tech Support at support@chattrboxx.com.";
		}
		
//		print_r($carrier_extension2);
//		exit;
		
		$userphone = $clean_phonenumber . '@' . $carrier_extension;
		if (isset($carrier_extension2) && $carrier_extension2 !="") {
			echo "Carrier 2 exists and is set...";
			$userphone2 = $clean_phonenumber . '@' . $carrier_extension2;	
		} else {
			echo "No Carrier 2 exists";
		}
		exit;
		//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;
        
		//echo "Phone: " . $clean_phonenumber . " | Carrier: " . $clean_carrier . " | Msg: " . $clean_message;
        
//		echo $userphone;
//		exit;
        
        // Let's send the email/text!
		if (isset($userphone) && $userphone !="") {
			$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: BASE Pages <contact@base.basepages.com>' . "\r\n";
			$headers .= 'Reply-To: BASE Pages <contact@base.basepages.com>';
			
			$email_recipient = $userphone; // SMS
			$email_recipient2 = $userphone2; // MMS
			$email_title = "Free SMS Text Verification";	
			$email_title2 = "Free MMS Text Verification";				
			$email_body = $clean_message;				

			//@mail($email_recipient, $email_title, $email_body, $headers,'-fcontact@chattrboxx.com');
			//@mail($email_recipient2, $email_title2, $email_body, $headers,'-fcontact@chattrboxx.com');

			//$notifSent = 1;
			//echo 1;	
			
			// NOW, LET'S STICK IT IN OUR DB TO CREATE A NATIONAL REPOSITORY
			$db = Mysql::getInstance();
			//			$subscriber = $db->where("ver_code = ?", $code)
			//			->select_one("users", 'id');
			
			if (isset($_POST['send'])) {
				$send = 1;
			}
			
//			$db->insert("smsnumbers", [
//				'user_id' => $_SESSION['user']['id'],
//				'phone' => $clean_phonenumber,
//				'carrier' => $carrier,
//				'ip_address' => $ipaddress,
//				'date_created'  => date("Y-m-d H:i:s")]);	
//				
//			$db->insert("phone_numbers", [
//				'org_id' => $_SESSION['user']['id'],
//				'uid' => $_SESSION['user']['id'],
//				'phoneNo' => $clean_phonenumber,
//				'smscarrier' => $carrier,
//				'ip_address' => $ipaddress,
//				'send' => $send,
//				'date'  => date("Y-m-d H:i:s")]);					
			
			require 'views/content_pages/messagesent.tpl.php';
			//exit;
			//echo $rid['device_id']; // was id
			//echo 1; // was id
			//exit;		
		} else {
			echo 0;
		}
    }	     
    
	function sendTextClear(){
		header("Location: /api/push/sms.php");
		exit;
	}         
	
	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://base.basepages.com/auth/verify?v=GSIVSpw
    function verify(){
		// https://chattrboxx.com/auth/verify?c=12er2vef
//		echo "hi";
//		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: BASE Pages <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 BASE Pages.
                    <br /><br />
                    We will be in touch once we get closer to launching.
                    <br /><br />
                    Thank you,<br />
					- BASE Pages Team<br />
                    </div>"; 			
			//if(!empty($subemail)){
				mail($subscriber_email, "You're reserved! Thanks!", $msg, $headers,"-fcontact@basepages.com");    
			//} else {
			//     mail("preorderforsquare@gmail.com", "Your Pre-Order Equity Partner Code!", $msg, $headers,"-fcontact@getpreorder.com");
			//}
						
			
			//header('Location: /vip-success');
			exit;
		}		
		
		//mail("sillystats@gmail.com", "Subscriber Alert2!", "You have a new Subscriber!", "From: Pre-Order <contact@getpreorder.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 rando(){
//		$randomIndex = mt_rand(1, 10);
//		echo $randomIndex;
//	}
//	function test(){
//		$params = session_get_cookie_params();
//		print_r($params);
//		Array ( [lifetime] => 0 [path] => / [domain] => [secure] => [httponly] => )
//	}
}
?>