<?php
// LEGACY PROFILES WITH /PROFILE/USERNAME
class ProfileController extends baseController {
    function index() {

        global $website_options;

		$projectModel = new projectModel();
        $squareuserModel = new squareusersModel();
		$user = $squareuserModel->getUser(['user_slug' => $this->registry->args[1]]);
		//print_r($user);

        if (! $user) {
            header("Location: /home?msg=" . urlencode("This user does not exist!"));
            exit;
        }		
		
		//$notificationsModel = new notificationsModel();
		
    	// $myProjects = $projectModel->getList(['user_id' => $_SESSION['user']['id']]);

		if ($_SESSION['loggedin'] && isset($_GET['follow'])) {
			$follow_status = $squareuserModel->followUser([
	    		'follower' => $_SESSION['user']['id'],
	    		'followed' => $user['id']
	    	]);
			
			if ($follow_status == 0) {
				//header('Location: /profile/'.$user['user_slug']);
				//header("Refresh: 5; URL=https://flipmob.com");
				//header('Location: /profile/'.$user['user_slug'].'?alreadyfollowing');
				//header('Location: /profile/'.$user['user_slug'].'?alreadyfollowing');
				$link = "https://flipmob.com/profile/".$user['user_slug']."?alreadyfollowing";
				//$link = "https://flipmob.com/profile/".$user['user_slug'];
				header("Refresh: 1; URL=$link");
				//echo "You already follow this account.";
	    	} else {
				//header('Location: /profile/'.$user['user_slug']);
				// ORIG header("Refresh: 5; URL=$url1");
				//header("Refresh: 5; URL=https://flipmob.com/profile/'.$user['user_slug'].'");
				header("Refresh: 1; URL=https://flipmob.com");
	    	}
    	}

		if ($_SESSION['loggedin'] && isset($_GET['unfollow'])) {
			$squareuserModel->unfollowUser([
    			'follower' => $_SESSION['user']['id'],
    			'followed' => $user['id']
    		]);
			header('Location: /profile/'.$user['user_slug']);
    	}

		if ($_SESSION['user']['id'])
			$isFollowed = $squareuserModel->isFollowed([
				'follower' => $_SESSION['user']['id'],
        		'followed' => $user['id']
        	]);
        	
			//print_r($isFollowed);

    	$user['projects'] = $projectModel->getList(['user_id' => $user['id']]);
		//$user['notifications'] = $notificationsModel->getMyNotifications(['user_id' => $user['id']]);
		//print_r($user['projects']);
		
		$user['followers'] = $squareuserModel->getFollowers(['followed' => $user['id']]);

		foreach ($user['followers'] as $index => $follow) {
			$user['followers'][$index] = $squareuserModel->getUser(['id' => $follow['user_id_follower']]);
    	}
    	
		if (!empty($_POST)) {
			// form sent - send introductions.
			$invited_users = $_POST['invited_users'];
			$squareuserModel->introduceUsers($user['id'],$invited_users);
			//print_r($invited_users);
			//introduceUsers($user_id,$member_ids){
				
			//foreach ($invited_users as $uid)
			//	$projectModel->inviteUser($project['id'], $uid);

			header("Location: /profile/" . $user['user_slug'] . "?intro");
			exit;
		}

        //$current_user_projects = [];
        //if ($_SESSION['loggedin'] && $_SESSION['user']['id']) {
        //    $current_user_projects = $projectModel->getList(['user_id' => $_SESSION['user']['id'], 'status' => 'created']);
        //}
        //$paypal_website_email = "contact@thinapp.co"; //"greg@evias.be";
        //$instagram_client_id  = "d2be0080a6e24ecbb8e0c75dd64488ea";

    	include ('views/profile/view.tpl.php');
    }
    
    function editMADE4() {
        global $website_options;

	   	if (!isset($_SESSION['user_id']) || !isset($_SESSION['loggedin']) || !$_SESSION['user_id'] || !$_SESSION['loggedin']) {
    		header("Location: " . get('siteroot'));
    		exit;
    	}
    	$userModel     = new userModel();
        //$projectModel  = new projectModel();
		$uploadsModel   = new uploadsModel();     

    	$user = $userModel->getUser(['id' => $_SESSION['user_id']]);
//    	print_r($_SESSION['user_id']);
//    	exit;
    	
        if ($_POST) {
            $userModel->updateUser($_SESSION['user_id'], $_POST, $_FILES);        
          	header("Location: /profile/edit");
            exit;
        }    	

        //$favorites = $usersModel->getFavorites($_SESSION['user_id']);    		
    	
		//$cond['user_id'] = $_SESSION['user_id'];
		//$usr = $user['id'];
        //$myProjects = $projectModel->getList();
		
		if (isset($_GET['profileimagesDeleteFile'])) {
            $uploadsModel->deleteFile((int)$_GET['profileimagesDeleteFile']);
            header('Location: /profile/edit');
            exit;
        }		

    	include ('views/profile/edit.tpl.php');
    }

    function edit() {
        global $website_options;

	   	if (!isset($_SESSION['user']['id']) || !isset($_SESSION['loggedin']) || !$_SESSION['user']['id'] || !$_SESSION['loggedin']) {
    		header("Location: " . get('siteroot'));
    		exit;
    	}
    	
    	$squareusersModel= new squareusersModel();
        $user = $squareusersModel->getSquareUser(['id' => $_SESSION['user']['id']]);
		$uploadsModel   = new uploadsModel();   
        
        if ($_POST) {
            $squareusersModel->updateUser($_SESSION['user']['id'], $_POST, $_FILES);
            header("Location: /profile/edit?msg");
            exit;
        }    	

        $favorites = $squareusersModel->getFavorites($_SESSION['user']['id']);
		$referrals = $squareusersModel->getReferrals($_SESSION['user']['ref']);
		$referralclicks = $squareusersModel->getReferralClicks($_SESSION['user']['ref']);
		//$user['images']
        
		if (isset($_GET['delete'])) {
			$squareusersModel->delete($_GET['delete']);
			unset($_SESSION['loggedin']);
			unset($_SESSION['user']['id']);
			unset($_SESSION['user']);
			header('Location: /');
			exit;
		}  
		
		if (isset($_GET['profileimagesDeleteFile'])) {
			$uploadsModel->deleteFile((int)$_GET['profileimagesDeleteFile']);
			header('Location: /profile/edit');
			exit;
		}		
        //echo "<pre>";
        //print_r($favorites);

    	include ('views/profile/edit.tpl.php');
    }
    
    function manage() {
        global $website_options;

	   	if (!isset($_SESSION['user']['id']) || !isset($_SESSION['loggedin']) || !$_SESSION['user']['id'] || !$_SESSION['loggedin']) {
    		header("Location: " . get('siteroot'));
    		exit;
    	}
    	
    	$squareusersModel= new squareusersModel();
        $user = $squareusersModel->getSquareUser(['id' => $_SESSION['user']['id']]);
		$uploadsModel   = new uploadsModel();   
        
        if ($_POST) {
            $squareusersModel->updateUser($_SESSION['user']['id'], $_POST, $_FILES);
             header("Location: /profile/edit?msg");
             exit;
        }    	

        $favorites = $squareusersModel->getFavorites($_SESSION['user']['id']);
		$referrals = $squareusersModel->getReferrals($_SESSION['user']['ref']);
		$referralclicks = $squareusersModel->getReferralClicks($_SESSION['user']['ref']);
		//$user['images']
        
		if (isset($_GET['delete'])) {
			$squareusersModel->delete($_GET['delete']);
			unset($_SESSION['loggedin']);
			unset($_SESSION['user']['id']);
			unset($_SESSION['user']);
			header('Location: /');
			exit;
		}  
		
		if (isset($_GET['profileimagesDeleteFile'])) {
			$uploadsModel->deleteFile((int)$_GET['profileimagesDeleteFile']);
			header('Location: /profile/edit');
			exit;
		}		
        //echo "<pre>";
        //print_r($favorites);

    	include ('views/profile/manage.tpl.php');
    }
    
    function editLastCoord() {
    	if (!isset($_SESSION['user']['id']) || !isset($_SESSION['loggedin']) || !$_SESSION['user']['id'] || !$_SESSION['loggedin']) {
    		header("Location: " . get('siteroot'));
    		exit;
    	}
		$squareuserModel = new squareusersModel();
		if ($_GET) {
			$squareuserModel->updateUserLastLocation($_SESSION['user']['id'],  $_GET['lat'],$_GET['lng']
    		);
    	}
    	include ('views/profile/edit.tpl.php');
    }

    function registerBusiness()
    {
        $projectModel = new projectModel();
        $usertypeModel = new usertypeModel();

        include ('views/profile/register-business.tpl.php');
    }

    function unreadNotificationsCount()
    {
        if (! $_SESSION['user']['id']) {
            echo "-1";
            exit;
        }

        $notificationsModel = new notificationsModel();
        $notificationsNow = $notificationsModel->unreadNotificationsCount($_SESSION['user']['id']);

        echo $notificationsNow;
        exit;
    }

    function unreadMessagesCount()
    {
        if (! $_SESSION['user']['id']) {
            echo "-1";
            exit;
        }

        $messagesModel = new messagesModel();
        $messagesNow = $messagesModel->unreadCount($_SESSION['user']['id']);

        echo $messagesNow;
        exit;
    }

    function upload()
    {
        $response = array('status' => 'error');
        if (!empty($_FILES['ufile'])) {
            do {
                $file = $_FILES['ufile'];
                if ($file['error']) {
                    $response['code'] = 1;
                    break;
                }

                if ($file['size'] > 1024*1024*10) {
                    $response['code'] = 2;
                    break;
                }

                $type = null;
                if (!empty($_POST['type']))
                    $type = $_POST['type'];

                $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ['php', 'htm', 'html', 'php4', 'php5', 'htaccess'])) {
                    $response['code'] = 3;
                    break;
                }

                if ($type == 'image' && ($ext != 'jpg' && $ext != 'png' && $ext != 'jpeg')) {
                    $response['code'] = 4;
                    break;
                }

                $filename = sha1($file['tmp_name']);

                $destination = "static/uploads/users/$filename.$ext";
                if (!file_exists($destination)) {
                    //if ($type == 'image') {
                    //    autoRotateImage($file['tmp_name']);
                    //}

                    move_uploaded_file($file['tmp_name'], $destination);
                }

                $uploadsModel = new uploadsModel();
                $id = $uploadsModel->insert($destination, $type, $file['name']);

                $response['status'] = 'ok';
                $response['id'] = $id;
            } while (0);
        }

        echo json_encode($response);
        exit;
    }
    function fillCheckboxSettings(array $fields, array $settings)
    {
        foreach ($fields as $field) {
            if (empty($settings[$field]))
                $settings[$field] = "0";
            else
                $settings[$field] = "1";
        }
        return $settings;
    }

    function transformMulti(array $fields, array $settings)
    {
        foreach ($fields as $field) {
            if (empty($settings[$field]))
                $settings[$field] = "";
            else
                $settings[$field] = implode(",", $settings[$field]);
        }
        return $settings;
    }

    function saveSettings()
    {
        if (empty($_POST['guest_settings']) || empty($_POST['user_hash']))
            exit;

        $settings  = $_POST['guest_settings'];
        $user_hash = $_POST['user_hash'];

        $settings_json = json_encode($settings);

        $db = Mysql::getInstance();
        $db->where("user_hash = ?", $user_hash);
        $db->order_by("date_created DESC");
        $db->limit(1);
        $exists = $db->select_one("guest_settings", 'id')['id'];

        if ($exists)
            $db->where("user_hash = ?", $user_hash)
               ->update("guest_settings", [
                    'settings_json' => $settings_json,
                    'date_updated'  => time()]);
        else
            $db->insert("guest_settings", [
                'user_hash'     => $user_hash,
                'settings_json' => $settings_json]);

        echo "OK";
        exit;
    }
	
    function sendMessage()
    {
        if (! $_SESSION['loggedin'] || ! $_SESSION['user']['id'] || (empty($_GET['to']) && empty($_POST['to']))) {
            header("Location: /auth/login");
            exit;
        }

        $to = $_POST ? $_POST['to'] : $_GET['to'];

        $model = new squareusersModel();
        $user  = $model->getUser($to);
        require 'views/messages/send-message.tpl.php';
    }	
    
    function updateVCodes(){
    	
		$_POST['ver_code'] = sha1("ChattrBoXX-" . time() . $_POST['email']);
    }
    
    function saveCarrier(){
    	
		//$user_id, $carrier
		$user_id = $_POST['user_id'];
		$carrier = $_POST['carrier'];
		//echo $user_id . ': ' . $carrier;

	    if (empty($user_id))
	        return false;
	    
		$db = Mysql::getInstance();
		$db->where("id = ?", $user_id)
		->update("users", [
			'carrier' => $carrier]);			
    }
    
	function verify(){
		// https://chattrboxx.com/profile/verify?c=12er2vef
//		echo "hi";
//		exit;
		
		$code = $_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!";

		require 'views/content_pages/phoneverified.tpl.php';
		//include ('views/profile/verified.tpl.php');
		//https://chattrboxx.com/phoneverified
	    //return $user_id;
	}    
	
	///////////////////////////////////////////////////////////////
	//    PAYMENT FEATURE - LOADING FUNDS TO ACCOUNT BALANCE	 //
	///////////////////////////////////////////////////////////////
		
	function payNow(){
		if ($_POST) {
			$_SESSION['chkout_item_descrip'] = $_POST['item_description'];
			$_SESSION['chkout_amount'] = $_POST['order_amount'];
			$_SESSION['chkout_coins'] = $_POST['order_coins'];
			
			echo 1;
		}
	}	
	
	function quickPurchase(){
		if (!$_SESSION['user_id']) {
			die('Not logged in');
		}
		
		$userModel = new squareusersModel();
		$user = $userModel->getUser(['id' => $_SESSION['user']['id']]);
		
		global $stripe_key;
		
		// PASSPHRASE ACCOUNT
		$stripe_key = "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";
		//$stripe_key = "sk_test_51LcyoIBKiPmjVaQdui1MzlB1nB4Ga2PcmxsafKZEwS6jEmrAzCmeIn3ZMpsZXBxPQDv3tV88c0Pj6we4T4MUbBZU0091ZOdvG0";

		require_once('3rdparty/stripenew/init.php');
		\Stripe\Stripe::setApiKey($stripe_key);

		//		print_r($user['stripe_id']);
		//		exit;

		$stripe = new \Stripe\StripeClient($stripe_key);

		if ($_POST) {
			//$updatedBalance = $_POST['amount'] + 100;
			//echo $_POST['amount'];
			//echo "-1";
			//exit;
			//echo json_encode(array("result"=> 2, "coins"=> $_POST['amount'], "new_balance"=> $updatedBalance));
			//exit;
			//echo "Quick Pay works...";

			// 'confirmation_method' => 'manual',
			$pmt_id = $_POST['payment_id'];
//			if (empty($pmt_id)) {
//				$pmt_id = "pm_1NbQk5BKiPmjVaQde6MsEPUN";
//			}
			$cust_id = $_POST['customer_id'];
//			if (empty($cust_id)) {
//				//$cust_id = "cus_ONeeWqd8GWKGPp"; // live cust ID for sillystats@gmail.com
//				$cust_id = "cus_ONJeoR5DxeUXYK"; // test cust ID for sillystats@gmail.com  
//			}
			$coins = $_POST['coins']; // coins purchased
			$coins_balance = $user['credits'];
			//$amount = $coins * 1.5;
			
			if ($coins < 5) {
				$amount = 100;
			} else if ($coins == 5) {
				$amount = 100;
			} else if ($coins > 5 && $coins < 50) {
				$amount = $coins * .10; // 
			} else if ($coins > 50 && $coins < 100) {
				$amount = $coins * .09; // 
			} else if ($coins > 100 && $coins < 250) {
				$amount = $coins * .08; // 
			} else if ($coins > 250 && $coins < 500) {
				$amount = $coins * .06; // 
			} else if ($coins > 500 && $coins < 1000) {
				$amount = $coins * .05; // 
			} else {
				$amount = $coins * .10;
			}	
			$amount_formatted = number_format($amount,2,".",",");
			$amount_cents = $amount * 100;
			$amount_int = number_format($amount_cents,0,"","");
			
			// FOR TESTING
			//echo json_encode(['success' => 1, 'coins' => $coins, 'payment_id' => $pmt_id, 'customer_id' => $cust_id, 'amount' => $amount_int]);
			
			//$intent->status = "succeeded"; // for testing
			try {
				// Create the PaymentIntent
				$intent = \Stripe\PaymentIntent::create([
					'payment_method_types' => ['card'],
					'amount' => $amount_int,
					'currency' => 'usd',
					'customer' => $cust_id,
					'payment_method' => $pmt_id,
					'confirm' => true,
					'error_on_requires_action' => true,
				]);
				// Now, Check to see if it worked...
				if ($intent->status == 'succeeded') {
					// Handle post-payment fulfillment
					$new_balance = $user['credits'] + $coins;
					$userModel->updateUser($_SESSION['user']['id'], ['credits' => $new_balance]);
					$userModel->insertPayment([
						'uid' 		=> $_SESSION['user']['id'],
						'fullname' 	=> $_SESSION['user']['name'],
						'email' 	=> $_SESSION['user']['email'],
						'item_description' => $coins . ' coins',
						'coins'   	=> $coins, 
						'amount'  	=> $amount_formatted,
						'transaction_id' => $intent->id
					]);
					$_SESSION['user']['credits'] = $new_balance;
					echo json_encode(['success' => 1, 'coins' => $new_balance, 'payment_id' => $pmt_id, 'customer_id' => $cust_id]);
				} else {
					// Any other status would be unexpected, so error
					echo json_encode(['error' => 1]);
				}
			} catch (\Stripe\Exception\ApiErrorException $e) {
				// Display error on client
				echo json_encode(['error' => $e->getMessage()]);
			} // END OF TRY CATCH
		} // END OF POST	
	} // END OF QUICK PURCHASE FUNCTION
	
	function qL(){
		$coins = 1;
		
//		if ($coins <= 5) {
//			$amount_calc = (5*1.029)+(30/100);
//		} else {
//			$amount_calc = ($coins * 1.029) + (30/100);
//		}
		
		$amount_calc = ($coins * 1.029) + (30/100);
		
		$amount_formatted = number_format($amount_calc,2,".",",");
		$amount_cents = $amount_calc * 100;
		$amount_int = number_format($amount_cents,0,"","");		

//		print_r($amount_cents);
		print_r($amount_int);
//		print_r($amount_formatted);
		exit;
	}
	
	function quickLoad(){
		if (!$_SESSION['user_id']) {
			die('Not logged in');
		}
		
		$userModel = new squareusersModel();
		$user = $userModel->getUser(['id' => $_SESSION['user']['id']]);
		
//		echo "<pre>";
//		print_r($user);
//		exit;
		// virtual_balance , ie. 2668000
		
		global $stripe_key;
		
		// PASSPHRASE ACCOUNT
//		$stripe_key = "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";
		$stripe_key = "sk_test_51NcbnqIjhpstBnMKmKyn2pv2TRadnwmuM878CudTl3tqVKc0qU5CqXMZVuVGgsCCJXFvIfC4Uz2RThideCRsxuHT0071sHTjmP";
		
		//pk_test_51NcbnqIjhpstBnMKeVZUtD4kmh0maxYPcnToCotuifg5XVEOcKjNkq0OQNSCKQjjWntzgWSysPPagSfMDzjUkQnp000qOqkkuY

		require_once('3rdparty/stripenew/init.php');
		\Stripe\Stripe::setApiKey($stripe_key);

		//		print_r($user['stripe_id']);
		//		exit;

		$stripe = new \Stripe\StripeClient($stripe_key);

		if ($_POST) {
			//$updatedBalance = $_POST['amount'] + 100;
			//echo $_POST['amount'];
			//echo "-1";
			//exit;
			//echo json_encode(array("result"=> 2, "coins"=> $_POST['amount'], "new_balance"=> $updatedBalance));
			//exit;
			//echo "Quick Pay works...";

			// 'confirmation_method' => 'manual',
			$pmt_id = $_POST['payment_id'];
//			if (empty($pmt_id)) {
//				$pmt_id = "pm_1NbQk5BKiPmjVaQde6MsEPUN";
//			}
			$cust_id = $_POST['customer_id'];
//			if (empty($cust_id)) {
//				//$cust_id = "cus_ONeeWqd8GWKGPp"; // live cust ID for sillystats@gmail.com
//				$cust_id = "cus_ONJeoR5DxeUXYK"; // test cust ID for sillystats@gmail.com  
//			}
			$coins = $_POST['coins']; // dollars to load
			$addtobalance_var = $coins * 100;
			$addtobalance = number_format($addtobalance_var,0,"","");	
			//$coins_balance = $user['credits']; // old, for credits
			$user_balance = $user['virtual_balance']; // new, for account balance
			//$amount = $coins * 1.5;
			
//			WHEN WE GO LIVE, SET THE MIN TO $5 OR 5 COINS
//			if ($coins <= 5) {
//				$amount_calc = (5*1.029)+(30/100);
//			} else {
//				$amount_calc = ($coins * 1.029) + (30/100);
//			}
			$amount_calc = ($coins * 1.029) + (30/100);
			
			$amount_formatted = number_format($amount_calc,2,".",",");
			$amount_cents = $amount_calc * 100;
			$amount_int = number_format($amount_cents,0,"","");	
			
			// FOR TESTING
			//echo json_encode(['success' => 1, 'coins' => $coins, 'payment_id' => $pmt_id, 'customer_id' => $cust_id, 'amount' => $amount_int]);
			
			//$intent->status = "succeeded"; // for testing
			try {
				// Create the PaymentIntent
				$intent = \Stripe\PaymentIntent::create([
					'payment_method_types' => ['card'],
					'amount' => $amount_int,
					'currency' => 'usd',
					'customer' => $cust_id,
					'payment_method' => $pmt_id,
					'confirm' => true,
					'error_on_requires_action' => true,
				]);
				// Now, Check to see if it worked...
				if ($intent->status == 'succeeded') {
					// Handle post-payment fulfillment
					$new_balance = $user_balance + $addtobalance;
					$userModel->updateUser($_SESSION['user']['id'], ['virtual_balance' => $new_balance]);
					$userModel->insertPayment([
						'id' 		=> $_SESSION['user']['id'],
						'fullname' 	=> $_SESSION['user']['name'],
						'email' 	=> $_SESSION['user']['email'],
						'item_description' => 'Load $' . $coins,
						'coins'   	=> $coins,
						'amount'  	=> $amount_formatted,
						'transaction_id' => $intent->id
					]);
					$_SESSION['user']['virtual_balance'] = $new_balance;
					echo json_encode(['success' => 1, 'coins' => $new_balance, 'payment_id' => $pmt_id, 'customer_id' => $cust_id]);
				} else {
					// Any other status would be unexpected, so error
					echo json_encode(['error' => 1]);
				}
			} catch (\Stripe\Exception\ApiErrorException $e) {
				// Display error on client
				echo json_encode(['error' => $e->getMessage()]);
			} // END OF TRY CATCH
		} // END OF POST	
	} // END OF QUICK PURCHASE FUNCTION
	
	function loadNEW(){
		if (!$_SESSION['user_id']) {
			//die('Not logged in');
			header("Location: /auth/login?msg=Please+log+in...");
			exit;
		}
		//global $stripe_key;
		
		$userModel = new squareusersModel();
		$user = $userModel->getUser(['id' => $_SESSION['user_id']]);
		//print_r($user);

		// pre-order
		//$stripe_key = "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";
		// PASSPHRASE ACCOUNT
		//$stripe_key = "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";
		
		//$stripe_key = "sk_test_51LcyoIBKiPmjVaQdui1MzlB1nB4Ga2PcmxsafKZEwS6jEmrAzCmeIn3ZMpsZXBxPQDv3tV88c0Pj6we4T4MUbBZU0091ZOdvG0";

		//require_once('3rdparty/stripenew/init.php');
		//\Stripe\Stripe::setApiKey($stripe_key); // so this still works and is the way to initialize Stripe
		
//		print_r($user['stripe_id']);
//		exit;
		
		//$stripe = new \Stripe\StripeClient($stripe_key); // oh, but this is used for the allPaymentsMethods

			
		include ('views/profile/load.tpl.php');
	}
	
	function load(){
		if (!$_SESSION['user_id']) {
			//die('Not logged in');
			header("Location: /auth/login?msg=Please+log+in...");
			exit;
		}
		global $stripe_key;
		
		$userModel = new squareusersModel();
		$user = $userModel->getUser(['id' => $_SESSION['user_id']]);

		// pre-order
		//$stripe_key = "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";
		// PASSPHRASE ACCOUNT
//		$stripe_key = "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";
		
		// WRONG KEY $stripe_key = "sk_test_51LcyoIBKiPmjVaQdui1MzlB1nB4Ga2PcmxsafKZEwS6jEmrAzCmeIn3ZMpsZXBxPQDv3tV88c0Pj6we4T4MUbBZU0091ZOdvG0";
		
		$stripe_key = "sk_test_51NcbnqIjhpstBnMKmKyn2pv2TRadnwmuM878CudTl3tqVKc0qU5CqXMZVuVGgsCCJXFvIfC4Uz2RThideCRsxuHT0071sHTjmP";

		require_once('3rdparty/stripenew/init.php');
		\Stripe\Stripe::setApiKey($stripe_key); // so this still works and is the way to initialize Stripe
		
//		print_r($user['stripe_id']);
//		exit;
		
		$stripe = new \Stripe\StripeClient($stripe_key); // oh, but this is used for the allPaymentsMethods
		
		if ($user['stripe_id']) {
			//echo "user exists...";
			
//			$stripe->paymentMethods->attach(
//			'pm_1NatLcBKiPmjVaQd9oEctqUR',
//			['customer' => 'cus_ONeeWqd8GWKGPp']
//			);
			
			//print_r($newcard);
			// PRODUCTION - PULL THE USER'S SAVED CARDS (IE. PAYMENT METHODS)
//			$cards = $stripe->customers->allPaymentMethods(
//			$user['stripe_id'],
//			  [
//			    'type' => 'card',
//			  ]
//			);
			// sillystats@gmail.com live customer - cus_OPaR6KcI8qKuTK
			//print_r($cards);
			
			// sillystats@gmail.com dev customer - cus_Pg9MsN0i14vmtl

			// DEVELOPMENT - TEST CARD(S)
			//https://api.stripe.com/v1/customers/cus_9s6XKzkNRiz8i3/payment_methods \
			
			$cards = $stripe->customers->allPaymentMethods(
			$user['stripe_id'],
				[
					'type' => 'card',
				]
			);
			
//			foreach ($paymentMethods->autoPagingIterator() as $paymentMethod) {
//			  // Do something with $paymentMethod
//			  print_r($paymentMethod);
//			}
			
			//			EXAMPLE https://stackoverflow.com/questions/72727913/how-can-get-the-array-of-stripe-customer-card-api-php
//			$stripe = new \Stripe\StripeClient('sk_test_123');
//			$paymentMethods = $stripe->customers->allPaymentMethods(
//			'cus_9utnxg47pWjV1e',
//			[
//				'type' => 'card',
//			]
//			);
//			foreach ($paymentMethods->autoPagingIterator() as $paymentMethod) {
//				// Do something with $paymentMethod
//			}
			
//			
//			$cards = \Stripe\Customer::retrieve($user['stripe_id'])->sources->all(array(
//			"object" => "card",
//			));
			///v1/customers/:id/sources
			
//			$cards = $stripe->customers->allPaymentMethods(
//			'cus_ONeeWqd8GWKGPp',
//			['type' => 'card']
//			);
			
//			$cards = $stripe->customers->allSources(
//				'cus_ONeeWqd8GWKGPp',
//				[
//					'object' => 'card',
//					'limit' => 3,
//				]
//			);
			
//			print_r($cards);
//			var_dump($cards);
		} else { 
			// IF THE LOGGED IN USER DOES NOT HAVE A STRIPE CUSTOMER ID IN THE SYSTEM
			// Create new customer
			
			try {
				$customer = \Stripe\Customer::create(array(
				'name'  => $user['name'],
				'email' => $user['email'],
				));
			} catch (Exception $e) {
				$error = $e->getMessage();
			}
			
//			$customer = \Stripe\Customer::create([
//				'email' => $user['email'],
//				'description' => $user['name'],
//			]);
			
			if ($customer) {
				$userModel->updateUser($_SESSION['user']['id'], ['stripe_id' => $customer->id]);
				//echo 'ok';
				//echo "Your card was saved successfully! Refresh this page to see it.";
			} else {
				//echo "Something went wrong. Check your card or try another.";
			}
		}
		
		// https://flipmob.com/profile/load?cardDeleted
		if (!empty($_GET['deleteCard'])) {
			$pmtID = $_GET['deleteCard'];
			//print_r($pmtID);
			
			if (!empty($pmtID)) {
				$stripe->paymentMethods->detach(
					$pmtID
				);
			}
			header("Location: /profile/load?cardDeleted");
			exit;
		}
			
		include ('views/profile/load.tpl.php');
	}	
	
	function credits(){
		if (!$_SESSION['user_id']) {
			//die('Not logged in');
			header("Location: /auth/login?msg=Please+log+in...");
			exit;
		}
		global $stripe_key;
		
		$userModel = new squareusersModel();
		$user = $userModel->getUser(['id' => $_SESSION['user_id']]);

		// PASSPHRASE ACCOUNT
		$stripe_key = "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";
		
		//$stripe_key = "sk_test_51LcyoIBKiPmjVaQdui1MzlB1nB4Ga2PcmxsafKZEwS6jEmrAzCmeIn3ZMpsZXBxPQDv3tV88c0Pj6we4T4MUbBZU0091ZOdvG0";

		require_once('3rdparty/stripenew/init.php');
		\Stripe\Stripe::setApiKey($stripe_key); // so this still works and is the way to initialize Stripe
		
//		print_r($user['stripe_id']);
//		exit;
		
		$stripe = new \Stripe\StripeClient($stripe_key); // oh, but this is used for the allPaymentsMethods
		
		if ($user['stripe_id']) {
			//echo "user exists...";
			
//			$stripe->paymentMethods->attach(
//			'pm_1NatLcBKiPmjVaQd9oEctqUR',
//			['customer' => 'cus_ONeeWqd8GWKGPp']
//			);
			
			//print_r($newcard);
			// PULL THE USER'S SAVED CARDS (IE. PAYMENT METHODS)
			$cards = $stripe->customers->allPaymentMethods(
			$user['stripe_id'],
			  [
			    'type' => 'card',
			  ]
			);
			
			//print_r($cards);

			// TEST CARD(S)
//			$cards = $stripe->customers->allPaymentMethods(
//			'cus_OOimzVS7GoZPmE',
//			[
//				'type' => 'card',
//			]
//			);
			
//			foreach ($paymentMethods->autoPagingIterator() as $paymentMethod) {
//			  // Do something with $paymentMethod
//			  print_r($paymentMethod);
//			}
			
//			
//			$cards = \Stripe\Customer::retrieve($user['stripe_id'])->sources->all(array(
//			"object" => "card",
//			));
			///v1/customers/:id/sources
			
//			$cards = $stripe->customers->allPaymentMethods(
//			'cus_ONeeWqd8GWKGPp',
//			['type' => 'card']
//			);
			
//			$cards = $stripe->customers->allSources(
//				'cus_ONeeWqd8GWKGPp',
//				[
//					'object' => 'card',
//					'limit' => 3,
//				]
//			);
			
//			print_r($cards);
//			var_dump($cards);
		} else { 
			// IF THE LOGGED IN USER DOES NOT HAVE A STRIPE CUSTOMER ID IN THE SYSTEM
			// Create new customer
			//echo "No Stripe Customer ID in the System";
			// UNHIDE THIS ONE
//			try {
//				$customer = \Stripe\Customer::create(array(
//				'name'  => $user['name'],
//				'email' => $user['email'],
//				));
//			} catch (Exception $e) {
//				$error = $e->getMessage();
//			}
			
			// FOR REFERENCE
//			$customer = \Stripe\Customer::create([
//				'email' => $user['email'],
//				'description' => $user['name'],
//			]);
			
			if ($customer) {
				//$userModel->updateUser($_SESSION['user']['id'], ['stripe_id' => $customer->id]);
				//echo 'ok';
				//echo "Your card was saved successfully! Refresh this page to see it.";
			} else {
				//echo "Something went wrong. Check your card or try another.";
			}
		}
			
		include ('views/profile/credits.tpl.php');
	}	
	
	function bids(){
		if (!$_SESSION['user_id']) {
			//die('Not logged in');
			header("Location: /auth/login?msg=Please+log+in...");
			exit;
		}
		global $stripe_key;
		
		$userModel = new squareusersModel();
		$user = $userModel->getUser(['id' => $_SESSION['user_id']]);

		// PASSPHRASE ACCOUNT
		$stripe_key = "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";
		
		//$stripe_key = "sk_test_51LcyoIBKiPmjVaQdui1MzlB1nB4Ga2PcmxsafKZEwS6jEmrAzCmeIn3ZMpsZXBxPQDv3tV88c0Pj6we4T4MUbBZU0091ZOdvG0";

		require_once('3rdparty/stripenew/init.php');
		\Stripe\Stripe::setApiKey($stripe_key); // so this still works and is the way to initialize Stripe
		
//		print_r($user['stripe_id']);
//		exit;
		
		$stripe = new \Stripe\StripeClient($stripe_key); // oh, but this is used for the allPaymentsMethods
		
		if ($user['stripe_id']) {
			//echo "user exists...";
			
//			$stripe->paymentMethods->attach(
//			'pm_1NatLcBKiPmjVaQd9oEctqUR',
//			['customer' => 'cus_ONeeWqd8GWKGPp']
//			);
			
			//print_r($newcard);
			// PULL THE USER'S SAVED CARDS (IE. PAYMENT METHODS)
			$cards = $stripe->customers->allPaymentMethods(
			$user['stripe_id'],
			  [
			    'type' => 'card',
			  ]
			);
			
			//print_r($cards);

			// TEST CARD(S)
//			$cards = $stripe->customers->allPaymentMethods(
//			'cus_OOimzVS7GoZPmE',
//			[
//				'type' => 'card',
//			]
//			);
			
//			foreach ($paymentMethods->autoPagingIterator() as $paymentMethod) {
//			  // Do something with $paymentMethod
//			  print_r($paymentMethod);
//			}
			
//			
//			$cards = \Stripe\Customer::retrieve($user['stripe_id'])->sources->all(array(
//			"object" => "card",
//			));
			///v1/customers/:id/sources
			
//			$cards = $stripe->customers->allPaymentMethods(
//			'cus_ONeeWqd8GWKGPp',
//			['type' => 'card']
//			);
			
//			$cards = $stripe->customers->allSources(
//				'cus_ONeeWqd8GWKGPp',
//				[
//					'object' => 'card',
//					'limit' => 3,
//				]
//			);
			
//			print_r($cards);
//			var_dump($cards);
		} else { 
			// IF THE LOGGED IN USER DOES NOT HAVE A STRIPE CUSTOMER ID IN THE SYSTEM
			// Create new customer
			//echo "No Stripe Customer ID in the System";
			// UNHIDE THIS ONE
//			try {
//				$customer = \Stripe\Customer::create(array(
//				'name'  => $user['name'],
//				'email' => $user['email'],
//				));
//			} catch (Exception $e) {
//				$error = $e->getMessage();
//			}
			
			// FOR REFERENCE
//			$customer = \Stripe\Customer::create([
//				'email' => $user['email'],
//				'description' => $user['name'],
//			]);
			
			if ($customer) {
				//$userModel->updateUser($_SESSION['user']['id'], ['stripe_id' => $customer->id]);
				//echo 'ok';
				//echo "Your card was saved successfully! Refresh this page to see it.";
			} else {
				//echo "Something went wrong. Check your card or try another.";
			}
		}
			
		include ('views/profile/bids.tpl.php');
	}	
	
	function synergies(){
		if (!$_SESSION['user_id']) {
			//die('Not logged in');
			header("Location: /auth/login?msg=Please+log+in...");
			exit;
		}
		
		$userModel = new squareusersModel();
		$user = $userModel->getUser(['id' => $_SESSION['user_id']]);
			
		include ('views/profile/synergies.tpl.php');
	}	
	
	function checkUsername(){
		//$ref = $_POST['ref'];
		//$ref = mysqli_real_escape_string($this->conn,$_POST['ref']);
		$db = Mysql::getInstance();
		$username = stripslashes(htmlentities($_POST['userslug']));
		$usernameid = $db->where("user_slug = ?", $username) // we also have ref in the table in the last column
		->select_one("users", 'id');

		if ($usernameid > 0) {
			echo 0; // Not Available
		} else {
			echo 1; // Available
		}
	}	
	
	function mylistings(){
		$categoryModel = new categoryModel();
		$listingModel  = new listingModel();
		$userModel     = new userModel();

		$projects = $listingModel->getMyListings($_SESSION['user']['id']);
		$categories = $categoryModel->getList();
		
		$fallback_coordinates = "{$projects[0]['location_lat']},{$projects[0]['location_lng']}";

		$current_user = null;
		$logged_in    = isset($_SESSION['user_id']) && isset($_SESSION['loggedin']) && $_SESSION['user_id'] && $_SESSION['loggedin'];

		if ($logged_in)
			$current_user = $userModel->getUser(['id' => $_SESSION['user_id']]);
		
		include ('views/profile/mylistings.tpl.php');
	}	
	
	function myfollowers(){
		
		global $website_options;

		$projectModel = new projectModel();
		$squareuserModel = new squareusersModel();
		$user = $squareuserModel->getUser($_SESSION['user']['id']);
		//print_r($user);

		if (!$user) {
			header("Location: /?msg=" . urlencode("This user does not exist!"));
			exit;
		}

		//$notificationsModel = new notificationsModel();

		// $myProjects = $projectModel->getList(['user_id' => $_SESSION['user']['id']]);

		if ($_SESSION['loggedin'] && isset($_GET['follow'])) {
			$follow_status = $squareuserModel->followUser([
				'follower' => $_SESSION['user']['id'],
				'followed' => $user['id']
			]);

			if ($follow_status == 0) {
				//header('Location: /profile/'.$user['user_slug']);
				//header("Refresh: 5; URL=https://flipmob.com");
				//header('Location: /profile/'.$user['user_slug'].'?alreadyfollowing');
				//header('Location: /profile/'.$user['user_slug'].'?alreadyfollowing');
				$link = "https://flipmob.com/profile/".$user['user_slug']."?alreadyfollowing";
				//$link = "https://flipmob.com/profile/".$user['user_slug'];
				header("Refresh: 1; URL=$link");
				//echo "You already follow this account.";
			} else {
				//header('Location: /profile/'.$user['user_slug']);
				// ORIG header("Refresh: 5; URL=$url1");
				//header("Refresh: 5; URL=https://flipmob.com/profile/'.$user['user_slug'].'");
				header("Refresh: 1; URL=https://flipmob.com");
			}
		}

		if ($_SESSION['loggedin'] && isset($_GET['unfollow'])) {
			$squareuserModel->unfollowUser([
				'follower' => $_SESSION['user']['id'],
				'followed' => $user['id']
			]);
			header('Location: /profile/'.$user['user_slug']);
		}

		if ($_SESSION['user']['id'])
			$isFollowed = $squareuserModel->isFollowed([
			'follower' => $_SESSION['user']['id'],
			'followed' => $user['id']
		]);

		//print_r($isFollowed);
		//$user['notifications'] = $notificationsModel->getMyNotifications(['user_id' => $user['id']]);
		$user['followers'] = $squareuserModel->getFollowers(['followed' => $user['id']]);

		foreach ($user['followers'] as $index => $follow) {
			$user['followers'][$index] = $squareuserModel->getUser(['id' => $follow['user_id_follower']]);
		}

		if (!empty($_POST)) {
			// form sent - send introductions.
			$invited_users = $_POST['invited_users'];
			$squareuserModel->introduceUsers($user['id'],$invited_users);
			//print_r($invited_users);
			//introduceUsers($user_id,$member_ids){

			//foreach ($invited_users as $uid)
			//	$projectModel->inviteUser($project['id'], $uid);

			header("Location: /profile/" . $user['user_slug'] . "?intro");
			exit;
		}

		
		include ('views/profile/myfollowers.tpl.php');
	}		
	
	function following(){
		
		global $website_options;

		$projectModel = new projectModel();
		$squareuserModel = new squareusersModel();
		$user = $squareuserModel->getUser($_SESSION['user']['id']);
		//print_r($user);

		if (!$user) {
			header("Location: /?msg=" . urlencode("This user does not exist!"));
			exit;
		}

		//$notificationsModel = new notificationsModel();

		// $myProjects = $projectModel->getList(['user_id' => $_SESSION['user']['id']]);

		if ($_SESSION['loggedin'] && isset($_GET['follow'])) {
			$follow_status = $squareuserModel->followUser([
				'follower' => $_SESSION['user']['id'],
				'followed' => $user['id']
			]);

			if ($follow_status == 0) {
				//header('Location: /profile/'.$user['user_slug']);
				//header("Refresh: 5; URL=https://flipmob.com");
				//header('Location: /profile/'.$user['user_slug'].'?alreadyfollowing');
				//header('Location: /profile/'.$user['user_slug'].'?alreadyfollowing');
				$link = "https://flipmob.com/profile/".$user['user_slug']."?alreadyfollowing";
				//$link = "https://flipmob.com/profile/".$user['user_slug'];
				header("Refresh: 1; URL=$link");
				//echo "You already follow this account.";
			} else {
				//header('Location: /profile/'.$user['user_slug']);
				// ORIG header("Refresh: 5; URL=$url1");
				//header("Refresh: 5; URL=https://flipmob.com/profile/'.$user['user_slug'].'");
				header("Refresh: 1; URL=https://flipmob.com");
			}
		}

		if ($_SESSION['loggedin'] && isset($_GET['unfollow'])) {
			$squareuserModel->unfollowUser([
				'follower' => $_SESSION['user']['id'],
				'followed' => $user['id']
			]);
			header('Location: /profile/'.$user['user_slug']);
		}

		if ($_SESSION['user']['id'])
			$isFollowed = $squareuserModel->isFollowed([
			'follower' => $_SESSION['user']['id'],
			'followed' => $user['id']
		]);

		//print_r($isFollowed);
		//$user['notifications'] = $notificationsModel->getMyNotifications(['user_id' => $user['id']]);
		$user['followers'] = $squareuserModel->getFollowers(['followed' => $user['id']]);

		foreach ($user['followers'] as $index => $follow) {
			$user['followers'][$index] = $squareuserModel->getUser(['id' => $follow['user_id_follower']]);
		}
		
		$user['following'] = $squareuserModel->getFollowing(['follower' => $user['id']]);

		foreach ($user['following'] as $index => $following) {
			$user['following'][$index] = $squareuserModel->getUser(['id' => $following['user_id_followed']]);
		}

		if (!empty($_POST)) {
			// form sent - send introductions.
			$invited_users = $_POST['invited_users'];
			$squareuserModel->introduceUsers($user['id'],$invited_users);
			//print_r($invited_users);
			//introduceUsers($user_id,$member_ids){

			//foreach ($invited_users as $uid)
			//	$projectModel->inviteUser($project['id'], $uid);

			header("Location: /profile/" . $user['user_slug'] . "?intro");
			exit;
		}

		
		include ('views/profile/following.tpl.php');
	}	
	
///////////////// END ///////////////// 
}