<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header('Content-Type: application/json');
date_default_timezone_set('Europe/London');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: api-token,user-api-token,device-name,device");

class MobileAPI extends MY_Controller {

	function __construct() {
		parent::__construct();

		$this->headers = $this->input->request_headers();

		$this->load->model('PBReusableModel_Security','appsecurity');
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			exit;
		}
		$this->load->model('PBReusableModel_Partners','partners');
		$this->load->model('PBReusableModel_User','users');
		$this->validPartner = null;

		// echo $this->router->method;
		if($this->router->method == "getWritingFeedFromWordpress" || $this->router->method == "getPodcastFeedFromWordpress" || $this->router->method == "getVideosFeedFromWordpress" || $this->router->method == "getVideosFeedFromYoutube") {
			// echo "hit here: ".$this->router->method;

		} else {
			$this->validPartner = $this->checkToken($this->headers);
			if(!$this->validPartner) {
				exit;
			}
		}


		// echo "Managed to hit here.";
		// var_dump($this->validPartner);
		// exit;

		$this->load->model('Auth_Model', 'auth');
		$this->load->library('encryption');

		$this->load->model('PBReusableModel_Analytics','analytics');
		$this->load->model('PBReusableModel_Global','globals');
		$this->load->model('PBReusableModel_User','users');
		$this->load->model('PBReusableModel_Wordpress','wordpress');
		$this->load->model('PBReusableModel_Wallet','wallet');
		$this->load->model('PBReusableModel_YouTube','youtube');
		$this->load->model('PBReusableModel_Mail','mail');
		$this->load->model('PBReusableModel_Notifications','notifications');
		// $this->load->database();
	}



	/* ********************************************************** */
	/* AUTH ***************************************************** */
	/* ********************************************************** */

	function checkAuthCode() {
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$user = $this->users->getFullUserByTokenFrontend($headers['User-Api-Token']);

            $user_object = $this->users->getUserObject($user['email']);

			echo json_encode(array('success' => true, 'message' => 'Auth code is valid for user', 'user' => $user_object));
		}
	}

	public function generateToken() {
		$data = $this->input->post();
		$token_info = $this->appsecurity->generateToken($data);
		if ($token_info) {
			echo json_encode(array('success' => true, 'message' => 'Successfully generated a new partner token', 'token' => $token_info));
		}
	}

	public function checkToken($headers) {
		if (isset($this->headers['Api-Token'])) {
			$valid = $this->partners->isTokenValid($this->headers['Api-Token']);
			if ($valid) {
				return $valid;
			} else {
				echo json_encode(array('success' => false, 'message' => 'Invalid Token'));
			}
		} else {
			echo json_encode(array('success' => false, 'message' => 'No token sent in header'));
		}
	}

	public function checkUserToken($headers) {
		if (isset($headers['User-Api-Token'])) {
			$api_token = $headers['User-Api-Token'];
			$valid = $this->users->isTokenValid($api_token);
			if ($valid) {
				return $valid;
			} else {
				echo json_encode(array('success' => false, 'message' => 'Invalid Token'));
			}
		} else {
			echo json_encode(array('success' => false, 'message' => 'No token sent in header'));
		}
	}

	/* ********************************************************** */
	/* HELLO ************************************************ */
	/* ********************************************************** */

    public function hello_world() {
        echo json_encode(array('success' => true, 'message' => 'Hello World!', 'context' => 'The API is working and ready to go'));
    }

	/* ********************************************************** */
	/* ANALYTICS ************************************************ */
	/* ********************************************************** */

	public function recordAnalyticPoint() {
try {

		$headers = $this->input->request_headers();
		// $validPartner = $this->checkToken($headers);
		if ($this->validPartner) {
			$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
			$this->analytics->recordAction(array(
				'date' => date('Y-m-d H:i:s'),
				'partner_id' => $this->validPartner[0]->id,
				'user_id' => $user['user_id'],
				'type' => $this->input->post('type'),
				'variable' => $this->input->post('variable'),
				'secondary_variable' => $this->input->post('secondary_variable')
			));
			echo json_encode(array('success' => true, 'message' => 'Successfully recorded the analytic'));
		} else {
			echo json_encode(array('success' => true, 'message' => 'Failed to record the analytic'));
		}
} catch (\Exception $e) {}

	}

	/* ********************************************************** */
	/* AMEMBER ************************************************** */
	/* ********************************************************** */

	function associateExistingAMemberAccountWithUser() {
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$user = $this->users->getUserByToken($headers['User-Api-Token']);
			if ($user) {
				$amember_response = json_decode($this->users->checkIfUserIsSubscribedOnLogin($this->input->post('amember_email'),$this->input->post('amember_password')), true);
				echo json_encode(array('success' => true, 'message' => 'Hello World!', 'context' => 'The API is working and ready to go', 'response' => $amember_response));
			}
		}
	}


	/* ********************************************************** */
	/* DEVICES ************************************************** */
	/* ********************************************************** */

	function associateNotificationTokenWithUser() {
		$headers = $this->input->request_headers();
		// Check that the api-token is included and is a valid token
		// $this->validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
			$assoc = array();
			$assoc['user_id'] = $user['user_id'];
			$assoc['device_token'] = $this->input->post('device_token');
			$assoc['device_type'] = $this->validPartner[0]->name;
			$associated = $this->users->associateNotificationTokenWithUser($assoc);
			if($associated == 1) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully associated the device token for user.',
					'context' => 'Everything was fine',
				));
			} else if($associated == 9) {
				echo json_encode(array(
					'success' => true,
					'message' => 'The device token was already associated with this user.',
					'context' => 'Everything was fine',
				));
				$this->analytics->recordAction(array(
					'date' => date('Y-m-d H:i:s'),
					'partner_id' => $this->validPartner[0]->id,
					'user_id' => $user['user_id'],
					'type' => 'AssociatePushToken',
					'variable' => $this->input->post('device_token'),
					'secondary_variable' => 0
				));
			} else {
				echo json_encode(array(
					'success' => false,
					'message' => 'Failed to associate the device token for user.',
					'context' => 'Could not add the device token',
				));
			}
		}
	}

	function unlinkDeviceForUser() {
		$headers = $this->input->request_headers();
		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			$unlinked = $this->users->unlinkDeviceForUser();
			if($unlinked) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully unlinked the device for user.',
					'context' => 'Everything was fine',
				));
				$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
				$this->analytics->recordAction(array(
					'date' => date('Y-m-d H:i:s'),
					'partner_id' => $this->validPartner[0]->id,
					'user_id' => $user['user_id'],
					'type' => 'UnlinkDevice',
					'variable' => $this->input->post('id'),
					'secondary_variable' => 0
				));
			} else {
				echo json_encode(array(
					'success' => false,
					'message' => 'Failed to unlink the device for user.',
					'context' => 'This device id wasnt found',
				));
			}
		}
	}

	function getDevicesForUser() {
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$devices = $this->users->getDevicesForUser($headers['User-Api-Token']);
			if($devices) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Got the devices for user.',
					'context' => 'Everything was fine',
					'devices' => $devices
				));
				// $validPartner = $this->checkToken($headers);
				// If the partner was valid; continue. Fail is handled by the checkToken function
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'ViewedDeviceList',
						'variable' => 0,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the devices for user.',
					'context' => 'Everything was fine',
					'devices' => null
				));
			}
		}
	}

	/* ********************************************************** */
	/* USER WALLET   ******************************************** */
	/* ********************************************************** */

	function creditUserAccount() {
		$headers = $this->input->request_headers();
		$credited = $this->wallet->creditUserAccount();
		if($credited) {
			$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
			echo json_encode(array(
				'success' => true,
				'message' => 'Your balance was topped up.',
				'context' => 'The users balance was topped up.',
				'wallet' => $wallet
			));
			// $validPartner = $this->checkToken($headers);
			if ($this->validPartner) {
				$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
				$this->analytics->recordAction(array(
					'date' => date('Y-m-d H:i:s'),
					'partner_id' => $this->validPartner[0]->id,
					'user_id' => $user['user_id'],
					'type' => 'CreditedUserAccount',
					'variable' => $this->input->post('value'),
					'secondary_variable' => $this->input->post('title')
				));
			}
		} else {
			$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
			echo json_encode(array(
				'success' => false,
				'message' => 'Your balance could not be topped up.',
				'context' => 'The users balance could not be topped up.',
				'wallet' => $wallet
			));
		}
	}

	function purchaseProduct() {
		$headers = $this->input->request_headers();
		// $validPartner = $this->checkToken($headers);
		if ($this->checkUserToken($headers)) {
			$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
			if ($wallet) {
				$purchase = $this->wallet->purchaseProduct($headers['User-Api-Token']);
				if($purchase == 9) {
					$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
					echo json_encode(array(
						'success' => false,
						'message' => 'Your balance was too low for this purchase.',
						'context' => 'The users balance was too low.',
						'wallet' => $wallet
					));
					if ($this->validPartner) {
						$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
						$this->analytics->recordAction(array(
							'date' => date('Y-m-d H:i:s'),
							'partner_id' => $this->validPartner[0]->id,
							'user_id' => $user['user_id'],
							'type' => 'AttemptedPurchaseLowBalance',
							'variable' => $this->input->post('product_id'),
							'secondary_variable' => 0
						));
					}
				} else if($purchase == 3) {
					$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
					echo json_encode(array(
						'success' => false,
						'message' => 'There was a problem purchasing this podcast.',
						'context' => 'The users balance was ok but there was a problem making the purchase.',
						'wallet' => $wallet
					));
				} else if($purchase == 6) {
					$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
					echo json_encode(array(
						'success' => false,
						'message' => 'You have already purchased this podcast.',
						'context' => 'The users has already purchased this podcast.',
						'wallet' => $wallet
					));
				} else if(!$purchase) {
					$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
					echo json_encode(array(
						'success' => false,
						'message' => 'Failed to purchase the product.',
						'context' => 'There was a server issue purchasing the product.',
						'wallet' => $wallet
					));
				} else {
					$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
					echo json_encode(array(
						'success' => true,
						'message' => 'Successfully made the purchase.',
						'context' => 'Everything was fine',
						'wallet' => $wallet
					));
					if ($this->validPartner) {
						$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
						$this->analytics->recordAction(array(
							'date' => date('Y-m-d H:i:s'),
							'partner_id' => $this->validPartner[0]->id,
							'user_id' => $user['user_id'],
							'type' => 'PurchasedProduct',
							'variable' => $this->input->post('product_id'),
							'secondary_variable' => 0
						));
					}
				}
			} else {
				echo json_encode(array(
					'success' => failed,
					'message' => 'Failed to purchase the product.',
					'context' => 'There was a problem getting the users wallet so was unable to make the purchase.',
				));
			}
		}
	}

	function getWalletForUser() {
		$headers = $this->input->request_headers();

		if ($this->checkUserToken($headers)) {
			$wallet = $this->wallet->getWalletForUser($headers['User-Api-Token']);
			if($wallet) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Got the wallet for user.',
					'context' => 'Everything was fine',
					'wallet' => $wallet
				));
				// $validPartner = $this->checkToken($headers);
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'ViewedWallet',
						'variable' => 0,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the wallet for user.',
					'context' => 'Everything was fine',
					'wallet' => null
				));
			}
		}
	}

	function getOrdersForUser() {
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$orders = $this->wallet->getOrdersForUser($headers['User-Api-Token']);
			if($orders) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Got the orders for user.',
					'context' => 'Everything was fine',
					'orders' => $orders
				));
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the orders for user.',
					'context' => 'Everything was fine',
					'orders' => null
				));
			}
		}
	}

	/* ********************************************************** */
	/* USER SERVICES ******************************************** */
	/* ********************************************************** */



	function checkIfEmailExists() {
		$headers = $this->input->request_headers();
		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			if ($this->users->checkIfEmailExists($this->input->post('email'))) {
				echo json_encode(array('success' => false, 'message' => 'Email address already exists in the database'));
			} else {
				echo json_encode(array('success' => true, 'message' => 'Email address is available'));
			}
		}
	}

	function resendActivationCode() {
		$resend = $this->users->resendActivationCode($this->input->post('email'));
		if($resend) {
			echo json_encode(array('success' => true, 'message' => 'Activation code successfully resent.'));
		} else {
			echo json_encode(array('success' => false, 'message' => 'Problem sending activation code'));
		}
	}

	function checkIfUsernameExists() {
		$headers = $this->input->request_headers();
		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			if ($this->users->checkIfUsernameExists($this->input->post('username'))) {
				echo json_encode(array('success' => false, 'message' => 'Username already exists in the database'));
			} else {
				echo json_encode(array('success' => true, 'message' => 'Username is available'));
			}
		}
	}

	function updateUsersAvatar() {
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
			$config['upload_path']   = './images/uploads/';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['file_name'] = $this->input->post('user_id').'_'.time();
			$config["width"] = 300;
			$config["height"] = 300;
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload('profile-avatar')) {
				$error = array('error' => $this->upload->display_errors());
				echo json_encode(array('success' => false, 'message' => $error));
			 } else {
				$file_data = array('upload_data' => $this->upload->data());
				$data = array();
				$data['user_id'] = $user['user_id'];
				$data['avatar'] = $file_data['upload_data']['file_name'];
				if ($this->users->updateTheUserAvatar($data)) {
					echo json_encode(array('success' => true, 'message' => 'Avatar updated', 'new_avatar' => base_url()."images/uploads/".$data['avatar']));
				} else {
					echo json_encode(array('success' => false, 'message' => 'Avatar update failed'));
				}
			 }
		}
	}

	public function getNotificationPreferencesForUser() {
		$preferences = $this->users->getNotificationPreferencesForUser();
		if ($preferences) {
			echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the preferences.',
					'context' => 'Everything was fine',
					'preferences' => $preferences
				));
		} else {
			echo json_encode(array(
				'success' => false,
				'message' => 'There was a problem getting your preferences. Please try again!',
				'context' => 'Failed to get the users preferences',
				'preferences' => null
			));
		}
	}

	public function updateNotificationPreferencesForUser($preference) {
		$updated = $this->users->updateNotificationPreferencesForUser($preference);
		if ($updated) {
			echo json_encode(array(
					'success' => true,
					'message' => 'Your preferences have now been updated.',
					'context' => 'Everything was fine'
				));
				$headers = $this->input->request_headers();
				// $validPartner = $this->checkToken($headers);
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'UpdatedNotificationSettings',
						'variable' => $preference,
						'secondary_variable' => $this->input->post('value')
					));
				}
		} else {
			echo json_encode(array(
				'success' => false,
				'message' => 'There was a problem updating your preferences. Please try again!',
				'context' => 'Failed to update the users preferences'
			));
		}
	}

	public function updateUsersEmail() {
		$headers = $this->input->request_headers();
		// $validPartner = $this->checkToken($headers);

		if ($this->checkUserToken($headers)) {
			$user = $this->users->getUserByToken($headers['User-Api-Token']);
			if ($user) {
				if ($user['email'] == $this->input->post('new_email') && $user['email'] == $this->input->post('old_email')) {
					echo json_encode(array(
						'success' => false,
						'message' => 'Your email address is already set to '.$user['email'],
						'context' => 'The new email address provided is the same as the existing email address so there is no update to be made.'
					));
				} else if ($user['email'] == $this->input->post('old_email')) {
					$updated = $this->users->updateUsersEmail();
					if($updated['success']) {
						echo json_encode(array(
							'success' => true,
							'message' => 'Your email address has been successfully updated.',
							'context' => ''
						));
						$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
						$this->analytics->recordAction(array(
							'date' => date('Y-m-d H:i:s'),
							'partner_id' => $this->validPartner[0]->id,
							'user_id' => $user['user_id'],
							'type' => 'UpdatedUserEmail',
							'variable' => $this->input->post('new_email'),
							'secondary_variable' => $this->input->post('old_email')
						));
					} else {
						if($updated['error'] = 809) {
							echo json_encode(array(
								'success' => false,
								'message' => 'There is already an account with that email. Please try to recover your acount!',
								'context' => 'There was already an account with the email '.$this->input->post('new_email').'.'
							));
						} else {
							echo json_encode(array(
								'success' => false,
								'message' => 'There was a problem updating your email address. Please try again!',
								'context' => 'There was a problem updating the email address.'
							));
						}
					}
				} else {
					echo json_encode(array(
						'success' => false,
						'message' => 'There was a problem updating your email address. Please try again!',
						'context' => 'The email address provided does not match the email address on file for the input token.'
					));
				}
			}
		}
	}

	public function updateUsersDetails() {
		$update = $this->users->updateUsersDetails();
		if ($update) {
			echo json_encode(array(
					'success' => true,
					'message' => 'Your details have now been updated.',
					'context' => 'Everything was fine'
				));
				$headers = $this->input->request_headers();
				// $validPartner = $this->checkToken($headers);
				$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
				$this->analytics->recordAction(array(
					'date' => date('Y-m-d H:i:s'),
					'partner_id' => $this->validPartner[0]->id,
					'user_id' => $user['user_id'],
					'type' => 'UpdatedUserDetails',
					'variable' => 0,
					'secondary_variable' => 0
				));
		} else {
			if ($update == -1) {
				echo json_encode(array(
					'success' => false,
					'message' => 'There was a problem updating your details. Please try again!',
					'context' => 'The token wasn\'t valid for the user'
				));
			} else {
				echo json_encode(array(
					'success' => false,
					'message' => 'There was a problem updating your details. Please try again!',
					'context' => 'Failed to update the users details'
				));
			}
		}

		// $headers = $this->input->request_headers();
		//
		// if ($this->checkUserToken($headers)) {
		// 	$user = $this->users->getUserByToken($headers['User-Api-Token']);
		// 	if ($user) {
		// 		// If email matches
		// 		if ($user['email'] == $this->input->post('email')) {
		// 			$update = $this->users->updateUsersDetails();
		// 			if ($update) {
		// 				echo json_encode(array('success' => true, 'message' => 'Users details successfully changed'));
		// 			} else {
		// 				echo json_encode(array('success' => false, 'message' => 'Failed to update the users details'));
		// 			}
		// 		} else {
		// 			$update = $this->users->updateUsersDetailsWithEmail($user['email']);
		// 			if ($update) {
		// 				echo json_encode(array('success' => true, 'message' => 'Users details successfully changed'));
		// 			} else {
		// 				echo json_encode(array('success' => false, 'message' => 'Failed to update the users details'));
		// 			}
		// 		}
		// 	} else {
		// 		echo json_encode(array('success' => false, 'message' => 'Could not find the user to match the token'));
		// 	}
		// }
	}

	public function changeTheUsersPassword() {
		$headers = $this->input->request_headers();
		// $validPartner = $this->checkToken($headers);
		if ($this->checkUserToken($headers)) {
			$user = $this->users->getUserByToken($headers['User-Api-Token']);
			if ($user) {
				$auth_data = $this->auth->get_auth_data($user['email']);
				// var_dump($auth_data);
				// Verify a matched password hash
				$auth = $this->authentication->check_passwd($auth_data->passwd, $this->input->post('old_password'));
				if ($auth) {
					if ($this->users->changeTheUsersPassword($user['email'])) {
						echo json_encode(array('success' => true, 'message' => 'Password successfully changed'));
						$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
						$this->analytics->recordAction(array(
							'date' => date('Y-m-d H:i:s'),
							'partner_id' => $this->validPartner[0]->id,
							'user_id' => $user['user_id'],
							'type' => 'ChangedUsersPassword',
							'variable' => 0,
							'secondary_variable' => 0
						));
					} else {
						echo json_encode(array('success' => false, 'message' => 'Password could not be changed'));
					}
				} else {
					echo json_encode(array('success' => false, 'message' => 'The old password is incorrect'));
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'FailedUsersPasswordChange',
						'variable' => 0,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array('success' => false, 'message' => 'Could not find the user to match the token'));
			}
		}
	}

	public function resetTheUsersPassword() {
		$headers = $this->input->request_headers();
		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			if ($this->users->checkIfEmailExists($this->input->post('email'))) {
				if ($this->users->isRecoveryCodeValid($this->input->post())) {
					if ($this->users->resetTheUsersPassword()) {
						echo json_encode(array('success' => true, 'message' => 'Password successfully reset'));
					} else {
						echo json_encode(array('success' => false, 'message' => 'Password could not be reset'));
					}
				} else {
					echo json_encode(array('success' => false, 'message' => 'Recovery code was incorrect'));
				}
			} else {
				echo json_encode(array('success' => false, 'message' => 'Email address does not exist in our database'));
			}
		}
	}

	public function recoverTheUser() {
		$headers = $this->input->request_headers();
		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			if ($this->users->checkIfEmailExists($this->input->post('email'))) {
				if ($this->users->recoverTheUser($this->input->post('email'))) {
					echo json_encode(array('success' => true, 'message' => 'Recovery code sent'));
				} else {
					echo json_encode(array('success' => false, 'message' => 'Recovery code could not be sent'));
				}
			} else {
				echo json_encode(array('success' => false, 'message' => 'Email address does not exist in our database'));
			}
		}
	}

	public function activateTheUser() {
		$headers = $this->input->request_headers();
		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			if ($this->users->isActivationCodeValid($this->input->post())) {
				$user = $this->users->activateTheUser($this->input->post());
				if ($user) {
					echo json_encode(array('success' => true, 'message' => 'Activation Successful'));
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => 0,
						'type' => 'ActivatedUserAccount',
						'variable' => $this->input->post('email'),
						'secondary_variable' => 0
					));
				} else {
					echo json_encode(array('success' => false, 'message' => 'Activation Failed'));
				}
			} else {
				echo json_encode(array('success' => false, 'message' => 'Activation Failed as the submitted values did not match'));
			}
		}
	}

	public function registerTheUser() {
		$headers = $this->input->request_headers();
		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			if ($this->users->checkIfEmailExists($this->input->post('email'))) {
				echo json_encode(array('success' => false, 'message' => 'There is already a registered user with the email address '.$this->input->post('email').'.'));
				$this->analytics->recordAction(array(
					'date' => date('Y-m-d H:i:s'),
					'partner_id' => $this->validPartner[0]->id,
					'user_id' => 0,
					'type' => 'FailedNewRegistration',
					'variable' => 'EmailExists',
					'secondary_variable' => $this->input->post('email')
				));
			} else if ($this->users->checkIfUsernameExists($this->input->post('username'))) {
				echo json_encode(array('success' => false, 'message' => 'There is already a registered user with the username '.$this->input->post('username').'.'));
				$this->analytics->recordAction(array(
					'date' => date('Y-m-d H:i:s'),
					'partner_id' => $this->validPartner[0]->id,
					'user_id' => 0,
					'type' => 'FailedNewRegistration',
					'variable' => 'UsernameExists',
					'secondary_variable' => $this->input->post('username')
				));
			} else {
				$new_user = $this->users->registerTheUser();
				if ($new_user) {
					echo json_encode(array('success' => true, 'message' => 'Registration Successful', 'user' => $new_user));
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => 0,
						'type' => 'NewRegistration',
						'variable' => $this->input->post('username'),
						'secondary_variable' => 0
					));
				} else {
					echo json_encode(array('success' => false, 'message' => 'There was a problem registering the user'));
				}
			}
		}
	}

	public function convertTheGuestUserToFullAccount() {
		$headers = $this->input->request_headers();
		// $validPartner = $this->checkToken($headers);
		$converted_user = $this->users->convertTheGuestUserToFullAccount();
		if ($converted_user) {
			echo json_encode(array('success' => true, 'message' => 'Guest to User conversion completed Successful', 'user' => $converted_user));
			$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
			// var_dump($user);
			$this->analytics->recordAction(array(
				'date' => date('Y-m-d H:i:s'),
				'partner_id' => $this->validPartner[0]->id,
				'user_id' => 0,
				'type' => 'ConvertedGuestToFullUser',
				'variable' => $user['user_id'],
				'secondary_variable' => 0
			));
		} else {
			echo json_encode(array('success' => false, 'message' => 'There was a problem converting the guest user to a full account'));
		}
	}

	public function registerTheGuestUser() {
		$headers = $this->input->request_headers();

		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			$new_user = $this->users->registerTheGuestUser();
			
			if ($new_user) {
				echo json_encode(array('success' => true, 'message' => 'Guest registration Successful', 'user_api_token' => $new_user['user_api_token'], 'username' => $new_user['username']));
				$this->analytics->recordAction(array(
					'date' => date('Y-m-d H:i:s'),
					'partner_id' => $this->validPartner[0]->id,
					'user_id' => 0,
					'type' => 'GuestRegistration',
					'variable' => $new_user['username'],
					'secondary_variable' => 0
				));
			} else {
				echo json_encode(array('success' => false, 'message' => 'There was a problem registering the guest user'));
			}

		}
	}

	public function logoutTheUser() {
		// var_dump($this->input->post());
		// Get the headers within the request
		$headers = $this->input->request_headers();
		// $validPartner = $this->checkToken($headers);
		// Check that the api-token is included and is a valid token
		// $valid_user = $this->checkUserToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		// if ($this->checkUserToken($headers)) {
		if ($this->appsecurity->deactivateUserToken($headers['User-Api-Token'])) {
			$this->users->removeTokenForUser($headers['User-Api-Token']);
			echo json_encode(array('success' => true, 'message' => 'Successfully logged out'));
			$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
			$this->analytics->recordAction(array(
				'date' => date('Y-m-d H:i:s'),
				'partner_id' => $this->validPartner[0]->id,
				'user_id' => $user['user_id'],
				'type' => 'LoggedOut',
				'variable' => 0,
				'secondary_variable' => 0
			));

			// 	echo json_encode(array('success' => false, 'message' => 'Failed to logout the user as the token or active state did not match the request.'));
			// }
		}
	}





	public function doThelogin() {
		$headers = $this->headers;
		// Check that the api-token is included and is a valid token
		// $validPartner = $this->checkToken($headers);
		// If the partner was valid; continue. Fail is handled by the checkToken function
		if ($this->validPartner) {
			// Store the partner_id for association if the user is logged in
			$partner_id = $this->validPartner[0]->id;
			// Check the required parameters are included within the request
			// if ($this->checkExpectedParametersForFunction('login')) {
			// Create a fresh array
			$data = array();
			// Get the current hash for the user attempting to be logged in
			$auth_data = $this->auth->get_auth_data($this->input->post('email'));
			if(!$auth_data) {
				echo json_encode(array('success' => false, 'message' => 'Auth data was not valid'));
				return;
			}
			if (!$this->users->checkIfEmailExists($this->input->post('email'))) {
				echo json_encode(array('success' => false, 'message' => 'The email address wasn\'t found in the database'));
				return;
			}

			// var_dump($auth_data);
			// echo "connection is made";
			// var_dump($this->authentication);
			// exit;
			// Verify a matched password hash
			$auth = $this->authentication->check_passwd($auth_data->passwd, $this->input->post('passwd'));
			// If login was successful
			if ($auth) {
				$token_data = array();
				$token_data['user_id'] = $auth_data->user_id;
				$token_data['partner_id'] = $partner_id;
				$token_data['user_agent'] = $headers['User-Agent'];
				$token_data['host'] = $headers['Host'];
				$token_data['unique_device_identifier'] = $headers['Device'];
				$token_data['last_logged_in'] = date('Y-m-d H:i:s');
				if(isset($headers['Device-Name'])) {
					$token_data['unique_device_name'] = $headers['Device-Name'];
				} else {
					$token_data['unique_device_name'] = "tempdevicename";
				}

				$auth_level = $auth_data->auth_level;
				$device_limit = 3;
				if($auth_level == 9) {
					$device_limit = 999;
				}
				// Check if the existing user-api token has been sent with the requests
				if (isset($headers['User-Api-Token'])) {
					// Check if the same device is trying to log in
					if($this->appsecurity->checkIfDeviceAndTokenIsAlreadyAssociatedWithUser($token_data['user_id'],$headers['User-Api-Token'],$token_data['unique_device_identifier'],$token_data['unique_device_name'])) {
						$new_auth_token = $headers['User-Api-Token'];
						// $validPartner = $this->checkToken($headers);
						if ($this->validPartner) {
							$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
							$this->analytics->recordAction(array(
								'date' => date('Y-m-d H:i:s'),
								'partner_id' => $this->validPartner[0]->id,
								'user_id' => $user['user_id'],
								'type' => 'LoggedInUsingExistingDevice',
								'variable' => $token_data['unique_device_name'],
								'secondary_variable' => $token_data['unique_device_identifier']
							));
						}
					} else {
						$existing_token = $this->appsecurity->checkIfDeviceIsAlreadyAssociatedWithUser($token_data['user_id'],$token_data['unique_device_identifier'],$token_data['unique_device_name']);
						if($existing_token) {
							$new_auth_token = $existing_token;
							// $validPartner = $this->checkToken($headers);
							if ($this->validPartner) {
								$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
								$this->analytics->recordAction(array(
									'date' => date('Y-m-d H:i:s'),
									'partner_id' => $this->validPartner[0]->id,
									'user_id' => $user['user_id'],
									'type' => 'LoggedInUsingExistingDevice',
									'variable' => $token_data['unique_device_name'],
									'secondary_variable' => $token_data['unique_device_identifier']
								));
							}
						} else {
							// echo "there are ".$this->appsecurity->countLinkedDevicesForUser($token_data['user_id'])." registered devices for this user";
							if($this->appsecurity->countLinkedDevicesForUser($token_data['user_id']) < $device_limit) {
								$new_auth_token = $this->appsecurity->generateUserToken($token_data);
								// $validPartner = $this->checkToken($headers);
								if ($this->validPartner) {
									$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
									$this->analytics->recordAction(array(
										'date' => date('Y-m-d H:i:s'),
										'partner_id' => $this->validPartner[0]->id,
										'user_id' => $user['user_id'],
										'type' => 'LoggedInUsingNewDevice',
										'variable' => $token_data['unique_device_name'],
										'secondary_variable' => $token_data['unique_device_identifier']
									));
								}
							} else {
								// $auth_data->user_id
								$devices = $this->users->getDevicesForUserID($auth_data->user_id);
								echo json_encode(array(
									'success' => false,
									'message' => 'You have reached your limit of devices for your account.',
									'context' => 'User has 3 devices linked already',
									'devices' => $devices
								));
								// $validPartner = $this->checkToken($headers);
								if ($this->validPartner) {
									$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
									$this->analytics->recordAction(array(
										'date' => date('Y-m-d H:i:s'),
										'partner_id' => $this->validPartner[0]->id,
										'user_id' => $user['user_id'],
										'type' => 'FailedLoginDueToNumberOfDevices',
										'variable' => $token_data['unique_device_name'],
										'secondary_variable' => $token_data['unique_device_identifier']
									));
								}
								return;
							}
						}
					}


					// if ($this->appsecurity->checkIfExistingTokenIsActive($token_data['user_id'],$headers['User-Api-Token'])) {
					// 	$new_auth_token = $headers['User-Api-Token'];
					// } else {
					// 	// Generate a new user token
					// 	$new_auth_token = $this->appsecurity->generateUserToken($token_data);
					// }
				} else {
					// echo "DEBUG 3";
					$existing_token = $this->appsecurity->checkIfDeviceIsAlreadyAssociatedWithUser($token_data['user_id'],$token_data['unique_device_identifier'],$token_data['unique_device_name']);
					if($existing_token) {
						// echo "DEBUG 4";
						$new_auth_token = $existing_token;
						// $validPartner = $this->checkToken($headers);
						if ($this->validPartner) {
							$user = $this->users->getFullUserByToken($existing_token);
							$this->analytics->recordAction(array(
								'date' => date('Y-m-d H:i:s'),
								'partner_id' => $this->validPartner[0]->id,
								'user_id' => $user['user_id'],
								'type' => 'LoggedInUsingExistingDevice',
								'variable' => $token_data['unique_device_name'],
								'secondary_variable' => $token_data['unique_device_identifier']
							));
						}
					} else {
						// echo "there are ".$this->appsecurity->countLinkedDevicesForUser($token_data['user_id'])." registered devices for this user";

						// echo "DEBUG 5".$existing_token;
						if($this->appsecurity->countLinkedDevicesForUser($token_data['user_id']) < $device_limit) {
							$new_auth_token = $this->appsecurity->generateUserToken($token_data);
						} else {
							$devices = $this->users->getDevicesForUserID($auth_data->user_id);

							// $devices = $this->users->getDevicesForUser($headers['User-Api-Token']);
							echo json_encode(array(
								'success' => false,
								'message' => 'You have reached your limit of devices for your account.',
								'context' => 'User has 3 devices linked already',
								'devices' => $devices
							));
							// $validPartner = $this->checkToken($headers);
							if ($this->validPartner) {
								$this->analytics->recordAction(array(
									'date' => date('Y-m-d H:i:s'),
									'partner_id' => $this->validPartner[0]->id,
									'user_id' => $auth_data->user_id,
									'type' => 'FailedLoginDueToNumberOfDevices',
									'variable' => $token_data['unique_device_name'],
									'secondary_variable' => $token_data['unique_device_identifier']
								));
							}
							return;
						}
					}
					// // Generate a new user token
					// $new_auth_token = $this->appsecurity->generateUserToken($token_data);
				}
				// Grab the user object
				$user_object = $this->users->getUserObject($this->input->post('email'));

				$token = $this->input->post('device_token');					// Get value from the API request
				$type = $this->input->post('device_type');						// Get value from the API request
				if (isset($token)) {											// Make sure the value is set
					if (isset($type)) {											// Make sure the value is set
						$udata = $this->input->post();							// Get all POST data and put it into a PHP array
						$udata['user_id'] = $auth_data->user_id;									// Set the user ID if not sent from the request
						$this->users->checkIfDeviceTokenForUserExists($udata);	// Check if the token already exists for the user
					}
				}
				$this->appsecurity->updateLastLoggedInDate($new_auth_token);
				
				
				// Login was valid
				echo json_encode(array('success' => true, 'message' => 'Successfully logged in', 'auth_token' => $new_auth_token, 'user' => $user_object));
			} else {
				// Failed login
				echo json_encode(array('success' => false, 'message' => 'Your username and/or password is incorrect.', 'context' => ''));
			}
		}
	}

	public function checkSubscriptionForUser() {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$subscription = $this->users->checkSubscriptionForUser($headers);
			// $success = $subscription['ok'];
			if($subscription) {
				echo json_encode(array('success' => true, 'message' => 'User has an active subscription', 'user' => $subscription));
			} else {
				echo json_encode(array('success' => false, 'message' => 'User is not currently subscribed'));
			}
		}
	}

	public function loginTheUser() {
		$amember_json = json_decode($this->users->checkIfUserIsSubscribedOnLogin($this->input->post('email'),$this->input->post('passwd')), true);
		if($amember_json) {
			// var_dump($amember_json);
			$success = $amember_json['ok'];
			if($success) {
				$this->users->createUserLocallyIfItDoesntExist($amember_json);
				return $this->doThelogin();
			} else {
				if($this->users->checkIfEmailExists($this->input->post('email'))) {
					// echo (int)$amember_json['code'];
					if((int)$amember_json['code'] == -2) {
						echo json_encode(array(
							"success" => false,
							"message" => "An account for this user has been found but the password was incorrect. Please reset your password on the app before attempting to login again."
						));
						exit;
					}
					if((int)$amember_json['code'] == -6) {
						echo json_encode(array(
							"success" => false,
							"message" => "No account for this user has been found. Please register before attempting to login."
						));
						exit;
					}
				} else {
					// echo (int)$amember_json['code'];
					if((int)$amember_json['code'] == -2) {
						echo json_encode(array(
							"success" => false,
							"message" => "An account for this user has been found but the password was incorrect. Please reset your password on the website before attempting to login again."
						));
						exit;
					}
					if((int)$amember_json['code'] == -6) {
						echo json_encode(array(
							"success" => false,
							"message" => "No account for this user has been found. Please register on the website or the app before attempting to login."
						));
						exit;
					}
				}

				// return $this->doThelogin();

			}
		}
		else
		{
			echo json_encode(array(
				"success" => false,
				"message" => "User has not subscribed to login."
			));
		}
	}

	/* ********************************************************** */

	public function getVideosFeedFromYoutube() {
		$videos = $this->youtube->getVideosFeedFromYoutube('');
		if($videos) {
			echo json_encode(array(
				'success' => true,
				'message' => 'Successfully got the videos feed from the YouTube API.',
				'context' => 'Everything is awesome!',
			));
		} else {
			echo json_encode(array(
				'success' => true,
				'message' => 'Failed to get the videos feed from the YouTube API.',
				'context' => 'There was a problem retrieving the videos',
			));
		}
	}

	/* ********************************************************** */
	/* WORDPRESS ************************************************ */
	/* ********************************************************** */

	public function getVideosFeedFromWordpress($page) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		$feed = $this->wordpress->getVideosFeedFromWordpress($page);
		if($feed) {
			echo json_encode(array(
				'success' => true,
				'message' => 'Successfully got the videos feed from the wordpress API.',
				'context' => 'Everything is awesome!',
				'feed' => $feed
			));
		} else {
			echo json_encode(array(
				'success' => true,
				'message' => 'Failed to get the videos feed from the wordpress API.',
				'context' => 'There was a problem retrieving the podcast feeds',
				'feed' => $feed
			));
		}
	}

	public function getVideosFeed($page,$limit) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$feed = $this->wordpress->getVideosFeed($page,$limit);
			if($feed) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the videos feed from the wordpress API.',
					'context' => 'Everything is awesome!',
					'feed' => $feed
				));
				// $validPartner = $this->checkToken($headers);
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'RequestedVideosFeed',
						'variable' => $page,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the videos feed from the wordpress API.',
					'context' => 'There was a problem retrieving the videos feeds',
					'feed' => $feed
				));
			}
		}
	}

	public function getPodcastFeed($page,$limit) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$feed = $this->wordpress->getPodcastFeed($page,$limit);
			if($feed) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the podcast feed from the wordpress API.',
					'context' => 'Everything is awesome!',
					'feed' => $feed
				));
				// $validPartner = $this->checkToken($headers);
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'RequestedPodcastFeed',
						'variable' => $page,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the podcast feed from the wordpress API.',
					'context' => 'There was a problem retrieving the podcast feeds',
					'feed' => $feed
				));
			}
		}
	}

	public function getPodcastFeedFromWordpress($page) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		// $headers = $this->input->request_headers();
		// if ($this->checkUserToken($headers)) {
			$feed = $this->wordpress->getPodcastFeedFromWordpress($page);
			if($feed) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the podcast feed from the wordpress API.',
					'context' => 'Everything is awesome!',
					'feed' => $feed
				));
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the podcast feed from the wordpress API.',
					'context' => 'There was a problem retrieving the podcast feeds',
					'feed' => $feed
				));
			}
		// }
	}

	public function getArticleByID($post_id) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$post = $this->wordpress->getArticleByID($post_id);
			if($post) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the article from the API.',
					'context' => 'Everything is awesome!',
					'article' => $post
				));
				// $validPartner = $this->checkToken($headers);
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'RequestedArticleByID',
						'variable' => $post_id,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the article from API.',
					'context' => 'There was a problem retrieving the article',
					'article' => $post
				));
			}
		}
	}

	public function getPodcastByID($post_id) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$post = $this->wordpress->getPodcastByID($post_id);
			if($post) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the podcast from the API.',
					'context' => 'Everything is awesome!',
					'podcast' => $post
				));
				// $validPartner = $this->checkToken($headers);
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'RequestedPodcastByID',
						'variable' => $post_id,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the podcast from API.',
					'context' => 'There was a problem retrieving the article',
					'podcast' => $post
				));
			}
		}
	}

	public function getVideoByID($post_id) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$post = $this->wordpress->getVideoByID($post_id);
			if($post) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the video from the API.',
					'context' => 'Everything is awesome!',
					'video' => $post
				));
				// $validPartner = $this->checkToken($headers);
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'RequestedVideoByID',
						'variable' => $post_id,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the article from API.',
					'context' => 'There was a problem retrieving the video',
					'video' => $post
				));
			}
		}
	}

	public function getWritingFeed($page,$limit) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		$headers = $this->input->request_headers();
		if ($this->checkUserToken($headers)) {
			$feed = $this->wordpress->getWritingFeed($page,$limit);
			if($feed) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the writing feed from the wordpress API.',
					'context' => 'Everything is awesome!',
					'feed' => $feed
				));
				// $validPartner = $this->checkToken($headers);
				if ($this->validPartner) {
					$user = $this->users->getFullUserByToken($headers['User-Api-Token']);
					$this->analytics->recordAction(array(
						'date' => date('Y-m-d H:i:s'),
						'partner_id' => $this->validPartner[0]->id,
						'user_id' => $user['user_id'],
						'type' => 'RequestedWritingFeed',
						'variable' => $page,
						'secondary_variable' => 0
					));
				}
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the writing feed from the wordpress API.',
					'context' => 'There was a problem retrieving the writing feeds',
					'feed' => $feed
				));
			}
		}
	}

	public function getWritingFeedFromWordpress($page) {
		if(!$this->appsecurity->inititateParameterCheck($this->router->method)) {
			return;
		}
		// $headers = $this->input->request_headers();
		// if ($this->checkUserToken($headers)) {
			$feed = $this->wordpress->getWritingFeedFromWordpress($page);
			if($feed) {
				echo json_encode(array(
					'success' => true,
					'message' => 'Successfully got the writing feed from the wordpress API.',
					'context' => 'Everything is awesome!',
					'feed' => $feed
				));
			} else {
				echo json_encode(array(
					'success' => true,
					'message' => 'Failed to get the writing feed from the wordpress API.',
					'context' => 'There was a problem retrieving the writing feeds',
					'feed' => $feed
				));
			}
		// }
	}

	/* ********************************************************** */

}
