<?php

class PBReusableModel_User extends CI_Model {

	const USERS = 'users';
	const USER_SEARCH = 'vw_user_search';
	const USERS_TOKENS = 'users_auth_tokens';
	const USERS_EMAILS = 'users_changed_emails';
	const DEVICE_TOKENS = 'user_device_tokens';
	const PARTNERS = 'sq_partners';
	const SUBSCRIPTIONS = 'taw_user_subscriptions';
	const USERS_PREFERENCES = 'taw_user_settings';
	const FREE_SUBSCRIPTIONS = 'subscription_free_plan';

    function __construct() {
        parent::__construct();
		// $this->load->database();
		$this->load->helper('date');
		$this->load->library('encryption');
		$this->load->helper('url');
		// $this->load->model('PBReusableModel_Mail','mail');
		// $this->load->model('PBReusableModel_Global','globals');
		// $this->load->model('PBReusableModel_Wallet','wallet');
    }

	// Devices
	function updateUserFromAMemberWebhook() {
return true;
		$postdata = $this->input->post();
		$user_array = $postdata['user'];

		$updated_user_array = array();
		$updated_user_array['username'] = $user_array['login'];
		$updated_user_array['firstname'] = $user_array['name_f'];
		$updated_user_array['lastname'] = $user_array['name_l'];
		$updated_user_array['email'] = $user_array['email'];

		log_message('error', $user_array['user']['user_id']);
		log_message('error', 'end');

		$data = array(
			"country" => $de
		);
		// $this->load->database();
		// $this->db->where("amember_user_id",'1070683490');
		// $this->db->update(self::USERS,$data);

		return true;
	}

	function searchUsersByKeywords($keywords) {
		$this->load->database();
		$this->db->select('user_id,username,email,firstname,lastname,
		(1.3 * MATCH(username) AGAINST ("'.$keywords.'*" IN BOOLEAN MODE)) as username_rank,
		(1.4 * MATCH(email) AGAINST ("'.$keywords.'*" IN BOOLEAN MODE)) as email_rank,
		(1.2 * MATCH(firstname) AGAINST ("'.$keywords.'*" IN BOOLEAN MODE)) as firstname_rank,
		(1.1 * MATCH(lastname) AGAINST ("'.$keywords.'*" IN BOOLEAN MODE)) as lastname_rank');
		$this->db->from(self::USER_SEARCH);
		$this->db->where('MATCH(username,email,firstname,lastname) AGAINST ("'.$keywords.'*" IN BOOLEAN MODE)');
		$this->db->order_by('email_rank DESC, username_rank DESC, firstname_rank DESC, lastname_rank DESC');
		$this->db->limit(50);
		$query = $this->db->get();
		return $query->result();
	}

	function associateNotificationTokenWithUser($data) {
		// var_dump($data);
		$assoc = $this->checkIfDeviceTokenForUserExists($data);
		return $assoc;
	}

	function unlinkDeviceForUser() {
		$data = $this->input->post();
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('id',$data['id']);
		$query = $this->db->get();
		$token = $query->row_array();
		if($token) {
			$this->load->database();
			$this->db->delete(self::USERS_TOKENS, array('id' => $data['id']));
			return 1;
		} else {
			return false;
		}
	}

	function getDevicesForUser($user_token) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_auth_token',$user_token);
		$query = $this->db->get();
		$user = $query->row_array();

		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_id',$user['user_id']);
		$query = $this->db->get();
		return $query->result();
	}

	function getDevicesForUserID($user_id) {

		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_id',$user_id);
		$query = $this->db->get();
		return $query->result();
	}

	// Admin

	function adminEditUser($user_id) {
		$data = $this->input->post();
		$this->load->database();
		$this->db->where("user_id",$user_id);
		$this->db->update(self::USERS,$data);
		return true;
	}

	function adminGetUser($user_id) {
		$this->load->database();
		$this->db->select('user_id,username,email,auth_level,created_at,modified_at,firstname,lastname,CONCAT("https://api-taw.pixelbeard.co/images/uploads/",avatar) as avatar,opt_in');
		$this->db->from(self::USERS);
		$this->db->where("user_id",$user_id);
		$this->db->limit(1);
		$query = $this->db->get();
		// if($query->num_rows()>0) {
		// 	return $query->row_array();
		// } else {
		// 	return null;
		// }
		if($query->num_rows()>0) {
			$users_array = array();
			foreach($query->result() as $user) {
				$user_array = array();
				$user_array['user_id'] = $user->user_id;
				$user_array['username'] = $user->username;
				$user_array['email'] = $user->email;
				$user_array['auth_level'] = $user->auth_level;
				$user_array['created_at'] = $user->created_at;
				$user_array['modified_at'] = $user->modified_at;
				$user_array['firstname'] = $user->firstname;
				$user_array['lastname'] = $user->lastname;
				$user_array['avatar'] = $user->avatar;
				$user_array['opt_in'] = $user->opt_in;

				$this->load->database();
				$this->db->select('*');
				$this->db->from(self::USERS_TOKENS);
				$this->db->where('user_id',$user->user_id);
				$query = $this->db->get();
				$user_array['devices'] = $query->result();

				$subs = $this->getUserSubscriptionsForAMember($user->user_id);
				$sub_array = array();
				foreach($subs as $sub) {
					$sub_data = array();
					$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
					$sub_data['subscription_expiry'] = $sub->subscription_expiry;
					array_push($sub_array,$sub_data);
				}
				$user_array['subscriptions'] = $sub_array;

				array_push($users_array,$user_array);
			}
            return $users_array;
		} else {
			return null;
		}
	}

	function countUsers($auth) {
		$this->load->database();
		$this->db->select('count(*) as count');
		$this->db->from(self::USERS);
		$this->db->order_by('created_at');
		$this->db->where('auth_level',$auth);
		$query = $this->db->get();
		$result = $query->row_array();
		return $result['count'];
	}

	function adminGetUsersPaginated($start,$auth) {
		$limit = 25;
		$start = $start -1;
		$page = $limit * $start;
		$this->load->database();
        $this->db->select('user_id,username,email,auth_level,created_at,modified_at,firstname,lastname,CONCAT("https://api-taw.pixelbeard.co/images/uploads/",avatar) as avatar,opt_in');
        $this->db->from(self::USERS);
		$this->db->limit($limit,$page);
		$this->db->where('auth_level',$auth);
		$this->db->order_by('created_at');
        $query = $this->db->get();
        if($query->num_rows()>0) {
			$users_array = array();
			foreach($query->result() as $user) {
				$user_array = array();
				$user_array['user_id'] = $user->user_id;
				$user_array['username'] = $user->username;
				$user_array['email'] = $user->email;
				$user_array['auth_level'] = $user->auth_level;
				$user_array['created_at'] = $user->created_at;
				$user_array['modified_at'] = $user->modified_at;
				$user_array['firstname'] = $user->firstname;
				$user_array['lastname'] = $user->lastname;
				$user_array['avatar'] = $user->avatar;
				$user_array['opt_in'] = $user->opt_in;

				$this->load->database();
				$this->db->select('*');
				$this->db->from(self::USERS_TOKENS);
				$this->db->where('user_id',$user->user_id);
				$query = $this->db->get();
				$user_array['devices'] = $query->result();

				$subs = $this->getUserSubscriptionsForAMember($user->user_id);
				$sub_array = array();
				foreach($subs as $sub) {
					$sub_data = array();
					$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
					$sub_data['subscription_expiry'] = $sub->subscription_expiry;
					array_push($sub_array,$sub_data);
				}
				$user_array['subscriptions'] = $sub_array;

				array_push($users_array,$user_array);
			}
            return $users_array;
        } else {
            return null;
        }
    }
	// Admin End

	public function getUserByEmail($email) {
		$this->load->database();
		$this->db->select('user_id');
		$this->db->from(self::USERS);
		$this->db->where('email',$email);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		return $user;
	}

	public function checkIfPartnerExists($user_id) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::PARTNERS);
		$this->db->where('user_id',$user_id);
		$query = $this->db->get();
		return $query->result();
	}

	public function registerThePartner() {
		$data = $this->input->post();
		$id = $this->get_unused_id();

		$register_data = array(
			'user_id' => $id,
			'username' => 'User'.$id,
			'firstname' => $data['firstname'],
			'lastname' => $data['lastname'],
			'email' => $data['email'],
			'passwd' => $this->authentication->hash_passwd($data['password']),
			'auth_level' => 6,
			'created_at' => date('Y-m-d H:i:s'),
			'modified_at' => date('Y-m-d H:i:s'),
			'opt_in' => true,
			'guest' => 0,
			'gender' => 3
		);

		$manager_data = array(
			'user_id' => $id,
			'brand_id' => $data['brand_id']
		);

		if($this->checkIfEmailExists($data['email'])) {
			$id = $this->getUserByEmail($data['email']);
			$id = $id['user_id'];
			// echo "user id existed and was ".$id;
			$this->db->where('user_id',$id);

			$update_data = array(
				'username' => 'User'.$id,
				'firstname' => $data['firstname'],
				'lastname' => $data['lastname'],
				'auth_level' => 6,
				'modified_at' => date('Y-m-d H:i:s'),
			);

			$updated_manager_data = array(
				'user_id' => $id,
				'brand_id' => $data['brand_id']
			);

			if ($this->db->update(self::USERS, $update_data)) {
				if($this->checkIfPartnerExists($id)){
					$this->db->where('user_id',$id);
					$this->db->update(self::PARTNERS, $updated_manager_data);
					return 3;
				} else {
					$this->db->insert(self::PARTNERS, $updated_manager_data);
					return 1;
				}
				return 3;
			} else {
				return 0;
			}
		} else {
			if ($this->db->insert(self::USERS, $register_data)) {
				if($this->checkIfPartnerExists($id)){
					$this->db->where('user_id',$manager_data['user_id']);
					$this->db->update(self::PARTNERS, $manager_data);
					return 3;
				} else {
					$this->db->insert(self::PARTNERS, $manager_data);
					return 1;
				}
				return 1;
			} else {
				return 0;
			}
		}
	}

	function removeTokenForUser($data) {
		$this->load->database();
		$this->db->delete(self::DEVICE_TOKENS, array('device_token' => $data));
		return 1;
	}

	function registerTokenForUser($data) {
		$token_data = array();
		$token_data['user_id'] = $data['user_id'];
		$token_data['device_token'] = $data['device_token'];
		$token_data['device_type'] = $data['device_type'];
		$this->db->insert(self::DEVICE_TOKENS, $token_data);
	}

	function checkIfDeviceTokenForUserExists($data) {
        $this->load->database();
        $this->db->select('*');
        $this->db->where('user_id', $data['user_id']);
        $this->db->where('device_token =', $data['device_token']);
		$this->db->from(self::DEVICE_TOKENS);
		$this->db->limit(1);
        $query = $this->db->get();
		if (!$query->row()) {
			$this->registerTokenForUser($data);
			return 1;
		} else {
			return 9;
		}
	}

	function getPushTokensForUser($user_id) {
		$this->load->database();
		$this->db->select('device_token');
		$this->db->where('user_id', $user_id);
		$this->db->from(self::DEVICE_TOKENS);
		$query = $this->db->get();
		return $query->result();
	}
	// Administration

	public function adminupdateUser($data) {
		$valid_data = array();
		$valid_data['modified_at'] = date('Y-m-d H:i:s');
		$valid_data['firstname'] = $data['firstname'];
		$valid_data['lastname'] = $data['lastname'];
		$valid_data['email'] = $data['email'];
		$valid_data['auth_level'] = $data['auth_level'];
		$valid_data['gender'] = $data['gender'];
		$this->load->database();
		$this->db->where('user_id',$data['user_id']);
		$this->db->update(self::USERS, $valid_data);
		$this->db->trans_complete();
		if($this->db->trans_status() === FALSE) {
		    return "0";
		} else {
			if ($this->db->affected_rows() > 0) {
				return "1";
			} else {
				return "2";
			}
		}
	}

	public function admin_registerTheUser() {
		$data = $this->input->post();

		$register_data = array(
			'user_id' => $this->get_unused_id(),
			'firstname' => $data['firstname'],
			'lastname' => $data['lastname'],
			'email' => $data['email'],
			'passwd' => $this->authentication->hash_passwd($data['password']),
			'auth_level' => $data['auth_level'],
			'created_at' => date('Y-m-d H:i:s'),
			'modified_at' => date('Y-m-d H:i:s'),
			'opt_in' => true,
			'gender' => $data['gender'],
		);
		$this->load->database();
		if ($this->db->insert(self::USERS, $register_data)) {
			return true;
		} else {
			return false;
		}
	}
	// Administration

	public function getFullUserObjectByID($id) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('user_id',$id);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		return $user;
	}

	// Datatable
	function users_count() {
		$this->load->database();
        $this->db->select('*');
        $this->db->from(self::USERS);
        $query = $this->db->get();
        return $query->num_rows();
    }

	function datatables_allusers($limit,$start,$col,$dir) {
		$this->load->database();
        $this->db->select('*');
        $this->db->from(self::USERS);
		$this->db->limit($limit,$start);
		$this->db->order_by($col,$dir);
        $query = $this->db->get();
        if($query->num_rows()>0) {
            return $query->result();
        } else {
            return null;
        }
    }

	function datatables_users_search($limit,$start,$search,$col,$dir) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->like('user_id',$search);
		$this->db->or_like('firstname',$search);
		$this->db->or_like('lastname',$search);
		$this->db->or_like('email',$search);
		$this->db->or_like('auth_level',$search);
		$this->db->limit($limit,$start);
		$this->db->order_by($col,$dir);
		$query = $this->db->get();
        if($query->num_rows()>0) {
            return $query->result();
        } else {
            return null;
        }
    }

	function datatables_users_search_count($search) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->like('user_id',$search);
		$this->db->or_like('firstname',$search);
		$this->db->or_like('lastname',$search);
		$this->db->or_like('email',$search);
		$this->db->or_like('auth_level',$search);
		$query = $this->db->get();
        return $query->num_rows();
    }
	// Datatable

	function getUsers() {
        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::USERS);
        $query = $this->db->get();
        return $query->result();
	}

	public function isTokenValid($token) {
        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::USERS_TOKENS);
		$this->db->where('user_auth_token',$token);
		$this->db->where('active',1);
        $query = $this->db->get();
        return $query->result();
	}

	public function getUserSubscriptionsForAMember($user_id) {
		$this->load->database();
        $this->db->select('*');
        $this->db->from(self::SUBSCRIPTIONS);
		$this->db->join(self::FREE_SUBSCRIPTIONS,'taw_user_subscriptions.subscription_auth_level=subscription_free_plan.subscription_auth_level');
		$this->db->where('taw_user_subscriptions.user_id',$user_id);
		$this->db->where('taw_user_subscriptions.amember_user_id !=',0);
		$this->db->limit(1);
		$this->db->order_by("taw_user_subscriptions.subscription_auth_level","DESC");
        $query = $this->db->get();
        return $query->result();
	}

	public function getCountOfUserSubscriptionsForAMember($user_id) {
		$this->load->database();
        $this->db->select('count(user_id) as count');
        $this->db->from(self::SUBSCRIPTIONS);
		$this->db->where('user_id',$user_id);
        $query = $this->db->get();
		$result = $query->row_array();
        return $result['count'];
	}

	public function getUserObject($user_string) {
		$selected_columns = [
			'email',
			'firstname',
			'lastname',
			'auth_level',
			'user_id',
			'banned',
			'avatar',
			'amember_user_id',
			'amember_email',
			'username'
			// 'guest',
		];
		$this->load->database();
		$this->db->select($selected_columns);
		$this->db->from(self::USERS);
		$this->db->where('LOWER(email) =',strtolower($user_string));
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		$user['avatar'] = base_url()."images/uploads/".$user['avatar'];
		$subs = $this->getUserSubscriptionsForAMember($user['user_id']);
		$free_subs = $this->getUserFreeSubscription($user['user_id']);
		$not_amember_sub = $this->getUserNotAmemberSubscription($user['user_id']);
		
		$total_subscription = $this->getCountOfUserSubscriptionsForAMember($user['user_id']);
		$sub_array = array();
		if($subs)
		{
			foreach($subs as $sub) {
				$sub_data = array();
				$sub_data['subscription_name'] = $sub->plan_name;
				$sub_data['subscription_status'] = $sub->subscription_expiry < date('Y-m-d') ? 'expired' : 'active';
				$sub_data['subscription_type'] = $sub->subscription_type;
				$sub_data['subscription_duration'] = $sub->subscription_duration;
				$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
				$sub_data['subscription_expiry'] = $sub->subscription_expiry;
				array_push($sub_array,$sub_data);
			}
		}
		elseif($free_subs)
		{
				$sub_data = array();
				$sub_data['subscription_name'] = $free_subs['plan_name'];
				$sub_data['subscription_status'] = $free_subs['subscription_expiry'] < date('Y-m-d') ? 'expired' : 'active';
				$sub_data['subscription_type'] = $free_subs['subscription_type'];
				$sub_data['subscription_duration'] = $free_subs['subscription_duration'];
				$sub_data['subscription_auth_level'] = $free_subs['subscription_auth_level'];
				$sub_data['subscription_expiry'] = $free_subs['subscription_expiry'];
				array_push($sub_array,$sub_data);

		}
		elseif($not_amember_sub)
		{	
				$sub_data = array();
				$sub_data['subscription_name'] = $not_amember_sub['plan_name'];
				$sub_data['subscription_status'] = $not_amember_sub['subscription_expiry'] < date('Y-m-d') ? 'expired' : 'active';
				$sub_data['subscription_type'] = $not_amember_sub['subscription_type'];
				$sub_data['subscription_duration'] = $not_amember_sub['subscription_duration'];
				$sub_data['subscription_auth_level'] = $not_amember_sub['subscription_auth_level'];
				$sub_data['subscription_expiry'] = $not_amember_sub['subscription_expiry'];
				array_push($sub_array,$sub_data);
			
		}
		
		

		if(isset($total_subscription) && $total_subscription>0)
		{
			$show_free_subscription = false;
		}
		else
		{
			$show_free_subscription = true;
		}
		$last_sub = $this->getLastExpiredSubByUserId($user['user_id']);
		$user['subscriptions'] = $sub_array;
		if($last_sub)
		{
			$user['is_sub_status'] = isset($last_sub['subscription_expiry']) ? ($last_sub['subscription_expiry'] < date('Y-m-d') ? 'expired' : 'active') : '';
			$user['last_sub_plan'] = isset($last_sub['plan_name']) ? $last_sub['plan_name'] : '';
			$user['last_sub_type'] = isset($last_sub['subscription_type']) ? $last_sub['subscription_type'] : '';
			$user['last_sub_auth'] = isset($last_sub['subscription_auth_level']) ? $last_sub['subscription_auth_level'] : '';
		}
		else
		{
			$user['is_sub_status'] = '';
			$user['last_sub_plan'] = '';
			$user['last_sub_type'] = '';
			$user['last_sub_auth'] = '';
		}
		
		$user['subscription_count'] = $total_subscription;
		$user['show_free_subscription'] = $show_free_subscription;
		return $user;
	}

	function getLastExpiredSubByUserId($user_id) {
		$this->load->database();
        $this->db->select('*');
        $this->db->from(self::SUBSCRIPTIONS);
		$this->db->join(self::FREE_SUBSCRIPTIONS,'taw_user_subscriptions.subscription_auth_level=subscription_free_plan.subscription_auth_level');
		$this->db->where('taw_user_subscriptions.user_id',$user_id);
		$this->db->where('taw_user_subscriptions.subscription_expiry <',date('Y-m-d'));
		$this->db->limit(1);
		$this->db->order_by("taw_user_subscriptions.subscription_expiry","DESC");
		$this->db->order_by("taw_user_subscriptions.subscription_auth_level","DESC");
        $query = $this->db->get();
        return $query->row_array();
	}

	function generateUserActivationCode() {
		$characters = 'ABCEFHJKMNPRTUVWXY493712568';
		$string = '';
		for ($i = 0; $i < 6; $i++) {
		    $string .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $string;
	}

	public function get_unused_id() {
        $this->load->database();
        // Create a random user id between 1200 and 4294967295
        $random_unique_int = 2147483648 + mt_rand( -2147482448, 2147483647 );
        // Make sure the random user_id isn't already in use
		$query = $this->db->get_where('users', array('user_id' => $random_unique_int), 1, 0);
        if( $query->num_rows() > 0) {
            $query->free_result();
            // If the random user_id is already in use, try again
            return $this->get_unused_id();
        }
        return $random_unique_int;
    }

	public function registerTheUser() {
		$data = $this->input->post();
		if ($data['opt_in'] == 'true') {
			$data['opt_in'] = 1;
		} else {
			$data['opt_in'] = 0;
		}
		$new_id = $this->get_unused_id();
		$register_data = array(
			'user_id' => $new_id,
			'firstname' => $data['firstname'],
			'lastname' => $data['lastname'],
			'email' => $data['email'],
			'passwd' => $this->authentication->hash_passwd($data['password']),
			'activation_code' => $this->users->generateUserActivationCode(),
			'auth_level' => 2,
			'created_at' => date('Y-m-d H:i:s'),
			'modified_at' => date('Y-m-d H:i:s'),
			'opt_in' => $data['opt_in'],
			'gender' => 3,
			'username' => $data['username'],
			'country' => $data['country']
		);
		$this->load->database();
		if ($this->db->insert(self::USERS, $register_data)) {
			$mail = array();
			$mail['email'] = $register_data['email'];
			$mail['activation_code'] = $register_data['activation_code'];
			$this->mail->sendActivationCodeEmail($mail);
			$this->registerUserToAMember($data);
			$this->createPrefsForUser($new_id);
			return $this->getUserObject($data['email']);
		} else {
			return false;
		}
	}

	public function convertTheGuestUserToFullAccount() {
		$user = $this->getUserByHeaders();
		$user_id = $user['user_id'];
        if ($this->globals->checkHeaders($user_id)) {
			$data = $this->input->post();
			$this->load->database();
			$this->db->select('*');
			$this->db->from(self::USERS);
			$this->db->where("user_id",$user_id);
			$code = $this->users->generateUserActivationCode();
			$register_data = array(
				'firstname' => $data['firstname'],
				'lastname' => $data['lastname'],
				'email' => $data['email'],
				'passwd' => $this->authentication->hash_passwd($data['password']),
				'activation_code' => $code,
				'auth_level' => 2,
				'created_at' => date('Y-m-d H:i:s'),
				'modified_at' => date('Y-m-d H:i:s'),
				'opt_in' => $data['opt_in'],
				'gender' => 3,
				'username' => $data['username'],
				'country' => $data['country']
			);
			$this->db->update(self::USERS,$register_data);
			if ($this->db->affected_rows() > 0) {
				$mail = array();
				$mail['email'] = $data['email'];
				$mail['activation_code'] = $code;
				$this->mail->sendActivationCodeEmail($mail);
				$this->registerUserToAMember($data);
				$this->createPrefsForUser($user_id);
				$this->wallet->creditFreeTokensToUserAccount();
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	public function getFullUserByIDForSubs($id) {
		$this->load->database();
		$this->db->select('email,amember_email');
		$this->db->from(self::USERS);
		$this->db->where('user_id',$id);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		return $user;
	}

	public function overwriteUserSubscriptionsWithLatestData($json) {
		
			$this->load->database();
			$this->db->select('*');
			$this->db->from(self::USERS);
			$this->db->where('amember_user_id',$json['user_id']);
			$this->db->limit(1);
			$query = $this->db->get();
			$row = $query->row_array();

			$this->load->database();
			$this->db->where('amember_user_id', $json['user_id']);
			$this->db->delete(self::SUBSCRIPTIONS);
			$subs = $json['subscriptions'];
			foreach($subs as $index => $id) {
				// echo "sub: ".$index." - ".$id;
				$subscription_data = array(
					'user_id' => $row['user_id'],
					'amember_user_id' => $json['user_id'],
					'subscription_auth_level' => $index,
					'subscription_expiry' => $id
				);
				$this->load->database();
				$this->db->insert(self::SUBSCRIPTIONS, $subscription_data);
			}	
		
		
		return $this->users->getUserObject($row['email']);
	}

	public function registerUserToAMember($data) {

		$url = 'https://www.theanfieldwrap.com/subscription/api/users';
		$fields = array(
		    '_key' => 'coBP0xqoap3R1g6o7beS',
		    'login' => $data['username'],
		    'pass' => $data['password'],
		    'email' => $data['email'],
		    'name_f' => $data['firstname'],
		    'name_l' => $data['lastname'],
		);
		//open connection
		$ch = curl_init();
		//set the url, number of POST vars, POST data
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
		curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));
		curl_setopt($ch, CURLOPT_USERAGENT, 'TAW Mobile API');

		//execute post
		$resp = curl_exec($ch);
		//close connection
		curl_close($ch);
	}
	public function getUserFreeSubscription($user_id){
		$this->load->database();
        $this->db->select('*');
        $this->db->from(self::SUBSCRIPTIONS);
		$this->db->join(self::FREE_SUBSCRIPTIONS,'taw_user_subscriptions.subscription_auth_level=subscription_free_plan.subscription_auth_level');
		$this->db->where('taw_user_subscriptions.user_id',$user_id);
		$this->db->where('taw_user_subscriptions.amember_user_id',0);
		$this->db->where('taw_user_subscriptions.subscription_type','free');
		$this->db->where('taw_user_subscriptions.subscription_expiry >=',date('Y-m-d'));
		$this->db->limit(1);
		$this->db->order_by("taw_user_subscriptions.subscription_auth_level","DESC");
        $query = $this->db->get();
		$user = $query->row_array();
		return $user;
	}

	public function getUserNotAmemberSubscription($user_id)
	{
		$this->load->database();
        $this->db->select('*');
        $this->db->from(self::SUBSCRIPTIONS);
		$this->db->join(self::FREE_SUBSCRIPTIONS,'taw_user_subscriptions.subscription_auth_level=subscription_free_plan.subscription_auth_level');
		$this->db->where('taw_user_subscriptions.user_id',$user_id);
		$this->db->where('taw_user_subscriptions.amember_user_id',0);
		$this->db->where('taw_user_subscriptions.subscription_type','paid');
		$this->db->where('taw_user_subscriptions.subscription_expiry >=',date('Y-m-d'));
		$this->db->limit(1);
		$this->db->order_by("taw_user_subscriptions.subscription_auth_level","DESC");
        $query = $this->db->get();
		$user = $query->row_array();
		return $user;
	}

	public function checkSubscriptionForUser() {
		$user_headers = $this->getUserByHeaders();
		$user = $this->getFullUserByIDForSubs($user_headers['user_id']);
		//  var_dump($user);
		$email = $user['email'];
		$curl = curl_init();
		curl_setopt_array($curl, array(
		    CURLOPT_RETURNTRANSFER => 1,
		    CURLOPT_URL => 'https://www.theanfieldwrap.com/subscription/api/check-access/by-email?_key=coBP0xqoap3R1g6o7beS&email='.urlencode($email),
		    CURLOPT_USERAGENT => 'TAW Mobile API'
		));
		$resp = curl_exec($curl);
		// var_dump($resp);

		curl_close($curl);
		$resp = json_decode($resp, true);
		// var_dump($resp);
		$subs = $this->getUserSubscriptionsForAMember($user_headers['user_id']);

		$sub_array = array();
		$free_sub_array = array();
		foreach($subs as $sub) {
			$sub_data = array();
			$sub_data['subscription_type'] = $sub->subscription_type;
			$sub_data['subscription_duration'] = $sub->subscription_duration;
			$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
			$sub_data['subscription_expiry'] = $sub->subscription_expiry;
			
			array_push($sub_array,$sub_data);
			
		}

		if(!isset($resp['ok']))
		{
			$resp['ok'] = false;
			$resp['subscriptions'] = [];
			$resp['user_id'] = '';
		}


		$free_sub_array = $this->getUserFreeSubscription($user_headers['user_id']);
		if($free_sub_array)
		{
			$resp['free_ok'] = true;
			$resp['free_subscriptions'] = $free_sub_array;
		}
		else
		{
			$resp['free_ok'] = false;
			$resp['free_subscriptions'] = array();

		}

		$not_amember_sub = $this->getUserNotAmemberSubscription($user_headers['user_id']);
		if($not_amember_sub)
		{
			$resp['sub_ok'] = true;
			$resp['not_amember_subscriptions'] = $not_amember_sub;
		}
		else
		{
			$resp['sub_ok'] = false;
			$resp['not_amember_subscriptions'] = array();

		}

		if($resp['ok'] || $resp['free_ok'] || $resp['sub_ok']) {
			if($resp['subscriptions'] && isset($resp['user_id'])) {
				return $this->overwriteUserSubscriptionsWithLatestData($resp);
			} 
			elseif($resp['not_amember_subscriptions'] || $resp['free_subscriptions']) {
				$this->load->database();
				$this->db->select('*');
				$this->db->from(self::USERS);
				$this->db->where('user_id',$user_headers['user_id']);
				$this->db->limit(1);
				$query = $this->db->get();
				$row = $query->row_array();
				return $this->users->getUserObject($row['email']);
			}
			else {
				return false;
			}
		} else {
			return false;
		}
	}

	public function checkIfUserIsSubscribedOnLogin($email,$password) {
		$curl = curl_init();
		curl_setopt_array($curl, array(
		    CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_URL => 'https://www.theanfieldwrap.com/subscription/api/check-access/by-email?_key=coBP0xqoap3R1g6o7beS&email=' . urlencode($email),
		    // CURLOPT_URL => 'https://www.theanfieldwrap.com/subscription/api/check-access/by-login-pass?_key=coBP0xqoap3R1g6o7beS&login='.$email.'&pass='.$password,
		    CURLOPT_USERAGENT => 'TAW Mobile API'
		));
		$resp = curl_exec($curl);
		curl_close($curl);
		// echo $resp;
		return $resp;
	}

	public function registerTheUserFromAMemberSingleSignOn($amember_json) {
		$data = $this->input->post();
		$data['opt_in'] = 0;
		$new_user_id = $this->get_unused_id();
		$register_data = array(
			'user_id' => $new_user_id,
			'amember_user_id' => $amember_json['user_id'],
			'firstname' => $amember_json['name_f'],
			'lastname' => $amember_json['name_l'],
			'email' => $data['email'],
			'amember_email' => $amember_json['email'],
			'passwd' => $this->authentication->hash_passwd($data['passwd']),
			'activation_code' => "",
			'auth_level' => 3,
			'created_at' => date('Y-m-d H:i:s'),
			'modified_at' => date('Y-m-d H:i:s'),
			'opt_in' => $data['opt_in'],
			'gender' => 0,
			// 'username' => $amember_json['login']
		);
		$this->load->database();
		if ($this->db->insert(self::USERS, $register_data)) {
			$headers = $this->input->request_headers();
			$token = $this->appsecurity->isAppTokenValid($headers['Api-Token']);
			if ($token) {
				$token_data = array();
				$token_data['user_id'] = $new_user_id;
				$token_data['partner_id'] = $token[0]->id;
				$token_data['user_agent'] = $headers['User-Agent'];
				$token_data['host'] = $headers['Host'];
				if(isset($headers['Device'])) {
					$token_data['unique_device_identifier'] = $headers['Device'];
				}
				if(isset($headers['Device-Name'])) {
					$token_data['unique_device_name'] = $headers['Device-Name'];
				}
				$new_auth_token = $this->appsecurity->generateUserToken($token_data);
				return $data['email'];
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public function createUserLocallyIfItDoesntExist($json) {
		$this->PDB1 = $this->load->database('default', TRUE);

		// $this->load->database();
        $this->PDB1->select('*');
        $this->PDB1->from(self::USERS);
		$this->PDB1->where('email',$json['email']);
		$this->PDB1->limit(1);
        $query = $this->PDB1->get();
		$row = $query->row_array();
        if($query->num_rows() > 0) {
			// user existed
			$this->load->database();
			$this->db->where('amember_user_id', $json['user_id']);
			$this->db->delete(self::SUBSCRIPTIONS);
			$subs = $json['subscriptions'];
			foreach($subs as $index => $id) {
				// echo "sub: ".$index." - ".$id;
				$subscription_data = array(
					'user_id' => $row['user_id'],
					'amember_user_id' => $json['user_id'],
					'subscription_auth_level' => $index,
					'subscription_expiry' => $id
				);
				$this->load->database();
				$this->db->insert(self::SUBSCRIPTIONS, $subscription_data);
			}
			$user = array();
			$user['amember_user_id'] = $json['user_id'];
			$user['amember_email'] = $json['email'];
			// var_dump($user);
			$this->load->database();
			$this->db->where("user_id",$row['user_id']);
			$this->db->update(self::USERS, $user);

			return $row['email'];
		} else {
			// user didnt exist so create
			return $this->registerTheUserFromAMemberSingleSignOn($json);;
		}
		// var_dump($json);
	}

	public function createPrefsForUser($user_id) {
		$p = array();
		$p['key'] = 'podcasts';
		$p['user_id'] = $user_id;
		$p['value'] = 1;
		// array_push($prefs_array,$p);

		$this->load->database();
		$this->db->select('user_id');
		$this->db->from(self::USERS_PREFERENCES);
		$this->db->where('user_id',$user_id);
		$this->db->where('key','podcasts');
		$query = $this->db->get();
		$presponse = $query->result();
		if(!$presponse) {
			$this->load->database();
			$this->db->insert(self::USERS_PREFERENCES, $p);
		}

		$p = array();
		$p['key'] = 'articles';
		$p['user_id'] = $user_id;
		$p['value'] = 1;
		// array_push($prefs_array,$p);

		$this->load->database();
		$this->db->select('user_id');
		$this->db->from(self::USERS_PREFERENCES);
		$this->db->where('user_id',$user_id);
		$this->db->where('key','articles');
		$query = $this->db->get();
		$presponse = $query->result();
		if(!$presponse) {
			$this->load->database();
			$this->db->insert(self::USERS_PREFERENCES, $p);
		}

		$p = array();
		$p['key'] = 'videos';
		$p['user_id'] = $user_id;
		$p['value'] = 1;
		// array_push($prefs_array,$p);

		$this->load->database();
		$this->db->select('user_id');
		$this->db->from(self::USERS_PREFERENCES);
		$this->db->where('user_id',$user_id);
		$this->db->where('key','videos');
		$query = $this->db->get();
		$presponse = $query->result();
		if(!$presponse) {
			$this->load->database();
			$this->db->insert(self::USERS_PREFERENCES, $p);
		}

		$p = array();
		$p['key'] = 'tawnews';
		$p['user_id'] = $user_id;
		$p['value'] = 1;
		// array_push($prefs_array,$p);

		$this->load->database();
		$this->db->select('user_id');
		$this->db->from(self::USERS_PREFERENCES);
		$this->db->where('user_id',$user_id);
		$this->db->where('key','tawnews');
		$query = $this->db->get();
		$presponse = $query->result();
		if(!$presponse) {
			$this->load->database();
			$this->db->insert(self::USERS_PREFERENCES, $p);
		}

		return true;
	}

	public function registerTheGuestUser() {
		$data = $this->input->post();
		$data['opt_in'] = 0;
		$new_user_id = $this->get_unused_id();
		$register_data = array(
			'user_id' => $new_user_id,
			'firstname' => "Guest".$new_user_id,
			'lastname' => "",
			'email' => "",
			'passwd' => "",
			'activation_code' => "",
			'auth_level' => 1,
			'created_at' => date('Y-m-d H:i:s'),
			'modified_at' => date('Y-m-d H:i:s'),
			'opt_in' => $data['opt_in'],
			'gender' => 0,
			'username' => 'Guest'.$new_user_id
		);
		$this->load->database();
		if ($this->db->insert(self::USERS, $register_data)) {
			$headers = $this->input->request_headers();
			$token = $this->appsecurity->isAppTokenValid($headers['Api-Token']);
			// var_dump($token);
			if ($token) {
				$token_data = array();
				$token_data['user_id'] = $new_user_id;
				$token_data['partner_id'] = $token[0]->id;
				$token_data['user_agent'] = $headers['User-Agent'];
				$token_data['host'] = $headers['Host'];
				// var_dump($headers);

				$token_data['unique_device_identifier'] = md5($new_user_id);
				$token_data['unique_device_name'] = md5($new_user_id);

				if(isset($headers['Device'])) {
					$token_data['unique_device_identifier'] = $headers['Device'];
				}
				if(isset($headers['Device-Name'])) {
					$token_data['unique_device_name'] = $headers['Device-Name'];
				}
				$new_auth_token = $this->appsecurity->generateUserToken($token_data);
				$guest = array();
				$guest['user_api_token'] = $new_auth_token;
				$guest['username'] = "Guest".$new_user_id;
				$this->createPrefsForUser($new_user_id);
				return $guest;
			} else {
				return false;
			}

		} else {
			return false;
		}
	}

	public function resendActivationCode($email) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('email',$email);
		$query = $this->db->get();
		$user = $query->row_array();
		$mail = array();
		$mail['email'] = $user['email'];
		$mail['activation_code'] = $user['activation_code'];
		$this->mail->sendActivationCodeEmail($mail);
		return true;
	}

	public function checkIfEmailExists($email) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('email',$email);
		$query = $this->db->get();
		return $query->result();
	}

	public function checkIfUsernameExists($username) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('username',$username);
		$query = $this->db->get();
		return $query->result();
	}

	public function isActivationCodeValid($data) {
        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::USERS);
		$this->db->where('activation_code',$data['activation_code']);
		$this->db->where('email',$data['email']);
        $query = $this->db->get();
        return $query->result();
	}

	public function activateTheUser($data) {
		$valid_data = array();
		$valid_data['auth_level'] = 3;
		$valid_data['modified_at'] = date('Y-m-d H:i:s');
		$valid_data['activation_code'] = '';
		// $valid_data['guest'] = '0';
		$this->load->database();
		$this->db->where('activation_code',$data['activation_code']);
		$this->db->where('email',$data['email']);
		$this->db->update(self::USERS, $valid_data);
		$this->db->trans_complete();
		if ($this->db->trans_status() === TRUE) {
			$this->wallet->creditFreeTokensToUserAccountOnActivation($data['email']);
			return true;
		} else {
			return false;
		}
	}

	public function recoverTheUser($email) {
		$valid_data = array();
		$valid_data['passwd_recovery_code'] = $this->users->generateUserActivationCode();
		$valid_data['passwd_recovery_date'] = date('Y-m-d H:i:s');
		$this->load->database();
		$this->db->where('email',$email);
		$this->db->update(self::USERS, $valid_data);
		$this->db->trans_complete();
		if ($this->db->trans_status() === TRUE) {
			$mail = array();
			$mail['email'] = $email;
			$mail['recovery_code'] = $valid_data['passwd_recovery_code'];
			$this->mail->sendForgottenDetailsEmail($mail);
			return true;
		} else {
			return false;
		}
	}

	public function isRecoveryCodeValid($data) {
        $this->load->database();
        $this->db->select('*');
        $this->db->from(self::USERS);
		$this->db->where('passwd_recovery_code',$data['recovery_code']);
		$this->db->where('email',$data['email']);
        $query = $this->db->get();
        return $query->result();
	}

	public function getUserByID($id) {
		$this->load->database();
		$this->db->select('email');
		$this->db->from(self::USERS);
		$this->db->where('user_id',$id);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		return $user;
	}

	public function getUserByToken($token) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_auth_token',$token);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		$email = $this->getUserByID($user['user_id']);
		return $email;
	}

	public function getUserByHeaders() {

		$headers = $this->input->request_headers();
		$user_token = "";
		if (isset($headers['User-Api-Token'])) {
			$user_token = $headers['User-Api-Token'];
		}

		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_auth_token',$user_token);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		// $email = $this->getUserByID($user['user_id']);
		return $user;
	}

	public function getFullUserByID($id) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('user_id',$id);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		return $user;
	}
	public function getUserObjectFrontend($user_id) {
		$selected_columns = [
			'email',
			'firstname',
			'lastname',
			'auth_level',
			'user_id',
			'banned',
			'avatar',
			'amember_user_id',
			'amember_email',
			'username'
		];
		$this->load->database();
		$this->db->select($selected_columns);
		$this->db->from(self::USERS);
		$this->db->where('user_id =',strtolower($user_id));
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		$user['avatar'] = base_url()."images/uploads/".$user['avatar'];
		$subs = $this->getUserSubscriptionsForAMember($user['user_id']);
		if($subs) {
			// var_dump($subs);
			$sub_array = array();
			foreach($subs as $sub) {
				// var_dump($sub);
				$sub_data = array();
				$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
				$sub_data['subscription_expiry'] = $sub->subscription_expiry;
				array_push($sub_data,$sub_array);
			}

			$user['subscriptions'] = $sub_array;
		} else {
			$sub_data = array();
			$sub_data['subscription_auth_level'] = 0;
			$sub_data['subscription_expiry'] = '';
			$user['subscriptions'] = $sub_data;
		}

		return $user;
	}
	public function getFullUserByTokenFrontend($token) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_auth_token',$token);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		$email = $this->getUserObjectFrontend($user['user_id']);
		return $email;
	}

	public function getFullUserByToken($token) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_auth_token',$token);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		$email = $this->getFullUserByID($user['user_id']);
		return $email;
	}

	public function checkPasswordEncryption() {
		return $this->authentication->hash_passwd($this->input->post('password'));
	}

	public function resetTheUsersPassword() {
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('email',$this->input->post('email'));
		$query = $this->db->get();
		$user = $query->row_array();
		$user_id = 0;
		if ($user) {
			$user_id = $user['amember_user_id'];
		}

		$valid_data = array();
		$valid_data['passwd_modified_at'] = date('Y-m-d H:i:s');
		$valid_data['passwd_recovery_code'] = '';
		$valid_data['passwd'] = $this->authentication->hash_passwd($this->input->post('password'));
		$this->load->database();
		$this->db->where('email',$this->input->post('email'));
		$this->db->update(self::USERS, $valid_data);
		$this->db->trans_complete();
		if ($this->db->trans_status() === TRUE) {
			$this->updatePasswordOnAMember($user_id,$this->input->post('password'));
			$this->mail->sendResetPasswordEmail($this->input->post('email'));
			return true;
		} else {
			return false;
		}
	}

	public function changeTheUsersPassword($email) {
		$valid_data = array();
		$valid_data['passwd_modified_at'] = date('Y-m-d H:i:s');
		$valid_data['passwd'] = $this->authentication->hash_passwd($this->input->post('new_password'));
		$this->load->database();
		$this->db->where('email',$email);
		$this->db->update(self::USERS, $valid_data);
		$this->db->trans_complete();
		if ($this->db->trans_status() === TRUE) {
			return true;
		} else {
			return false;
		}
	}

	public function getNotificationPreferencesForUser() {
		$user = $this->globals->getUserByHeaders();
		if($user) {
			$this->createPrefsForUser($user['user_id']);
			$this->load->database();
			$this->db->select('*');
			$this->db->from(self::USERS_PREFERENCES);
			$this->db->where('user_id',$user['user_id']);
			$query = $this->db->get();
			$response = $query->result();
			$prefs_array = array();
			if($response) {
				foreach($response as $pref) {
					$p = array();
					$p['key'] = $pref->key;
					$p['value'] = $pref->value;
					array_push($prefs_array,$p);
				}
			} else {
				$p = array();
				$p['key'] = 'podcasts';
				$p['user_id'] = $user['user_id'];
				$p['value'] = 1;
				array_push($prefs_array,$p);

				$this->load->database();
				$this->db->select('*');
				$this->db->from(self::USERS_PREFERENCES);
				$this->db->where('user_id',$user['user_id']);
				$this->db->where('key','podcasts');
				$query = $this->db->get();
				$presponse = $query->result();
				if(!$presponse) {
					$this->load->database();
					$this->db->insert(self::USERS_PREFERENCES, $p);
				}

				$p = array();
				$p['key'] = 'articles';
				$p['user_id'] = $user['user_id'];
				$p['value'] = 1;
				array_push($prefs_array,$p);

				$this->load->database();
				$this->db->select('*');
				$this->db->from(self::USERS_PREFERENCES);
				$this->db->where('user_id',$user['user_id']);
				$this->db->where('key','articles');
				$query = $this->db->get();
				$presponse = $query->result();
				if(!$presponse) {
					$this->load->database();
					$this->db->insert(self::USERS_PREFERENCES, $p);
				}

				$p = array();
				$p['key'] = 'videos';
				$p['user_id'] = $user['user_id'];
				$p['value'] = 1;
				array_push($prefs_array,$p);

				$this->load->database();
				$this->db->select('*');
				$this->db->from(self::USERS_PREFERENCES);
				$this->db->where('user_id',$user['user_id']);
				$this->db->where('key','videos');
				$query = $this->db->get();
				$presponse = $query->result();
				if(!$presponse) {
					$this->load->database();
					$this->db->insert(self::USERS_PREFERENCES, $p);
				}

				$p = array();
				$p['key'] = 'tawnews';
				$p['user_id'] = $user['user_id'];
				$p['value'] = 1;
				array_push($prefs_array,$p);

				$this->load->database();
				$this->db->select('*');
				$this->db->from(self::USERS_PREFERENCES);
				$this->db->where('user_id',$user['user_id']);
				$this->db->where('key','tawnews');
				$query = $this->db->get();
				$presponse = $query->result();
				if(!$presponse) {
					$this->load->database();
					$this->db->insert(self::USERS_PREFERENCES, $p);
				}

			}

			return $prefs_array;
		} else {
			return false;
		}
	}

	public function updateNotificationPreferencesForUser($preference) {
		$data = array();
		$data['key'] = $preference;
		$data['value'] = $this->input->post('value');
		$user = $this->globals->getUserByHeaders();
		if($user) {
			$data['user_id'] = $user['user_id'];
		}
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_PREFERENCES);
		$this->db->where('key',$preference);
		$this->db->limit(1);
		$query = $this->db->get();
		$existing_preference = $query->row_array();
		if($existing_preference) {
			$this->load->database();
			$this->db->where('key',$preference);
			$this->db->where('user_id',$user['user_id']);
			$this->db->update(self::USERS_PREFERENCES, $data);
			return true;
		} else {
			$this->load->database();
			$this->db->insert(self::USERS_PREFERENCES, $data);
			return true;
		}
		return false;
	}

	public function checkIfEmailExistsInAMember($user_id,$email) {
		$curl = curl_init();
		curl_setopt_array($curl, array(
		    CURLOPT_RETURNTRANSFER => 1,
		    CURLOPT_URL => 'https://www.theanfieldwrap.com/subscription/api/check-access/by-email?_key=coBP0xqoap3R1g6o7beS&email='.$email,
		    CURLOPT_USERAGENT => 'TAW Mobile API'
		));
		$resp = curl_exec($curl);
		curl_close($curl);
		$resp = json_decode($resp,true);
		return $resp['ok'];
	}

	public function updatePasswordOnAMember($user_id,$password) {

		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => 'https://www.theanfieldwrap.com/subscription/api/users/'.$user_id.'?_key=coBP0xqoap3R1g6o7beS&pass='.$password,
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 30,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "PUT",
		  CURLOPT_POSTFIELDS => "",
		  CURLOPT_HTTPHEADER => array(
		    "cache-control: no-cache"
		  ),
		));

		// $url = 'https://www.theanfieldwrap.com/subscription/api/users/'.$user_id.'?_key=coBP0xqoap3R1g6o7beS&pass='.$password;
		// $ch = curl_init();
		// curl_setopt($ch, CURLOPT_URL, $url);
		// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		// curl_setopt($ch, CURLOPT_PUT, true);
		// curl_setopt($ch, CURLOPT_USERAGENT, 'TAW Mobile API');
		$resp = curl_exec($curl);
		// var_dump($resp);
		curl_close($curl);
	}

	public function updateDetailsOnAMember($data) {
		$url = 'https://www.theanfieldwrap.com/subscription/api/users/'.$data['user_id'].'?_key=coBP0xqoap3R1g6o7beS&name_f='.$data['firstname'].'&name_l='.$data['lastname'].'&login='.$data['username'];
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_PUT, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 'TAW Mobile API');
		$resp = curl_exec($ch);
		curl_close($ch);
	}

	public function updateEmailOnAMember($user_id,$email) {
		$url = 'https://www.theanfieldwrap.com/subscription/api/users/'.$user_id.'?_key=coBP0xqoap3R1g6o7beS&email='.$email;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_PUT, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 'TAW Mobile API');
		$resp = curl_exec($ch);
		curl_close($ch);
	}

	public function updateUsersEmail() {
		$this->load->database();
		$valid_data = array();
		$valid_data['modified_at'] = date('Y-m-d H:i:s');
		$valid_data['email'] = $this->input->post('new_email');

		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('email',$this->input->post('old_email'));
		$query = $this->db->get();
		$user = $query->row_array();
		$user_id = 0;
		if ($user) {
			$user_id = $user['amember_user_id'];
		}
		if($this->checkIfEmailExistsInAMember($user_id,$this->input->post('new_email'))) {
			return array(
				"success" => false,
				"error" => 809
			);
		} else {
			$this->updateEmailOnAMember($user_id,$this->input->post('new_email'));
			$this->load->database();
			$this->db->where('email',$this->input->post('old_email'));
			$this->db->update(self::USERS, $valid_data);
			$this->db->trans_complete();
			if ($this->db->trans_status() === TRUE) {
				return array(
					"success" => true,
				);
			} else {
				return array(
					"success" => false,
				);
			}
		}
		return array(
			"success" => false,
		);
	}

	public function updateUsersDetails() {
		$user = $this->globals->getUserByHeaders();
		if($user) {
			$valid_data = array();
			$valid_data['modified_at'] = date('Y-m-d H:i:s');
			$valid_data['firstname'] = $this->input->post('firstname');
			$valid_data['lastname'] = $this->input->post('lastname');
			$valid_data['username'] = $this->input->post('username');
			$this->load->database();
			$this->db->where('user_id',$user['user_id']);
			$this->db->update(self::USERS, $valid_data);
			$this->db->trans_complete();
			if ($this->db->trans_status() === TRUE) {
				$valid_data['user_id'] = $user['user_id'];
				$this->updateDetailsOnAMember($valid_data);
				return true;
			} else {
				return false;
			}
		} else {
			return -1;
		}
	}

	public function updateUsersDetailsWithEmail($current_email) {
		$valid_data = array();
		$valid_data['modified_at'] = date('Y-m-d H:i:s');
		$valid_data['firstname'] = $this->input->post('firstname');
		$valid_data['lastname'] = $this->input->post('lastname');
		$valid_data['activation_code'] = $this->users->generateUserActivationCode();
		$valid_data['auth_level'] = 2;
		$valid_data['gender'] = $this->input->post('gender');
		$valid_data['email'] = $this->input->post('email');
		$this->load->database();
		$this->db->where('email',$current_email);
		$this->db->update(self::USERS, $valid_data);
		$this->db->trans_complete();
		if ($this->db->trans_status() === TRUE) {
			$user = $this->getUserObject($this->input->post('email'));
			$user['changed_email'] = $this->input->post('email');
			$mail = array();
			$mail['email'] = $this->input->post('email');
			$mail['activation_code'] = $valid_data['activation_code'];
			$this->mail->sendChangeEmailEmail($mail);
			// $this->requestEmailChangeForUser($user);
			return true;
		} else {
			return false;
		}
	}

	public function checkIfAnEmailRequestIsAlreadyActiveForUser($user_id) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_EMAILS);
		$this->db->where('user_id',$user_id);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		if ($user) {
			return true;
		} else {
			return false;
		}
	}

	public function updateTheUserAvatar($data) {
		$valid_data = array();
		$valid_data['modified_at'] = date('Y-m-d H:i:s');
		$valid_data['avatar'] = $data['avatar'];
		$valid_data['user_id'] = $data['user_id'];
		$this->load->database();
		$this->db->where('user_id',$data['user_id']);
		$this->db->update(self::USERS, $valid_data);
		$this->db->trans_complete();
		if ($this->db->trans_status() === TRUE) {
			return true;
		} else {
			return false;
		}

	}

	// AMember Updates Start

	public function associateRegisteredUserWithExistingAMemberUser() {

	}

	// AMember Updates End

	public function checkNewUser($token)
	{
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_auth_token',$token);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('user_id',$user['user_id']);
		$this->db->where('auth_level !=',1); //1 for guest
		$this->db->limit(1);
		$query1 = $this->db->get();
		if(!$query1->result())
		{
			return false;
		}
		else
		{
			$total_subscription = $this->getCountOfUserSubscriptionsForAMember($user['user_id']);
			if($total_subscription >0)
			{
				return false;
			}
			else
			{
				$userdetails = $query1->row_array();
				return $userdetails;
			}
		}
		
	}

	public function activateFreeSubscriptionForUser($user,$subs)
	{
		$type= $subs['type'];
		$plan_exist = $this->checkPlanExist($subs['plan'],$type);

		if($plan_exist)
		{

			if($subs['days'])
			{
				$expiry = date('Y-m-d', strtotime('+'.$subs['days'].' days'));
				$duration = $subs['days'];
			}
			elseif($subs['expiry'])
			{
				$expiry = $subs['expiry'];
				$diff= strtotime($subs['expiry'])-strtotime(date('Y-m-d'));
				$days =	abs(round($diff / 86400));
				$duration = $days;
			}
			else{

				$duration = 0;
				$expiry = null;
			}
			if($subs['entry_variable'])
			{
				$is_entry_var_exist = $this->checkIfAlreadyExistEntryOnSubscription($user['user_id'],$subs['entry_variable']);
			}
			else {
				$is_entry_var_exist = false;
			}

			if($is_entry_var_exist != true)
			{
				$subscription_data = array(
					'user_id' => $user['user_id'],
					'subscription_auth_level' => $subs['plan'],
					'subscription_expiry' => $expiry,
					'subscription_duration' => $duration,
					'subscription_type' => $subs['type'],
					"subscription_created_on" => date('Y-m-d H:i:s'),
					'entry_variable' => $subs['entry_variable']
				);
				$this->load->database();
				$this->db->insert(self::SUBSCRIPTIONS, $subscription_data);
			}
			return $this->getUserObject($user['email']);


		}
		else
		{
			return false;
		}
	}

	public function activatePaidSubscriptionForUser($subs)
	{

		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USERS_TOKENS);
		$this->db->where('user_auth_token',$subs['user-api-token']);
		$this->db->limit(1);
		$query = $this->db->get();
		$user = $query->row_array();
		
		$this->db->select('*');
		$this->db->from(self::USERS);
		$this->db->where('user_id',$user['user_id']);
		$this->db->where('auth_level !=',1);
		$this->db->limit(1);
		$query1 = $this->db->get();

		if(!$query1->result())
		{
			return false;
		}
		else
		{
			
			$userdetails = $query1->row_array();
		
		}
		$type = $subs['type'];
		$plan_exist = $this->checkPlanExist($subs['plan'],$type);
		if($plan_exist)
		{
			if($subs['days'])
			{
				$expiry = date('Y-m-d', strtotime('+'.$subs['days'].' days'));
				$duration = $subs['days'];
			}
			elseif($subs['expiry'])
			{
				$expiry = $subs['expiry'];
				$diff= strtotime($subs['expiry'])-strtotime(date('Y-m-d'));
				$days =	abs(round($diff / 86400));
				$duration = $days;
			}
			else{

				$duration = 0;
				$expiry = null;
			}

			if($subs['entry_variable'])
			{
				$is_entry_var_exist = $this->checkIfAlreadyExistEntryOnSubscription($userdetails['user_id'],$subs['entry_variable']);
			}
			else {
				$is_entry_var_exist = false;
			}

			if($is_entry_var_exist != true)
			{
				$subscription_data = array(
					'user_id' => $userdetails['user_id'],
					'subscription_auth_level' => $subs['plan'],
					'subscription_expiry' => $expiry,
					'subscription_duration' => $duration,
					'subscription_type' => $subs['type'],
					'subscription_created_on' => date('Y-m-d H:i:s'),
					'entry_variable' => $subs['entry_variable']
				);


				$this->load->database();
				$activate = $this->db->insert(self::SUBSCRIPTIONS, $subscription_data);
			}
			return $this->getUserObject($userdetails['email']);

		}
		else
		{
			return false;
		}
	}

	public function checkIfAlreadyExistEntryOnSubscription($user_id,$entry_var)
	{
		$this->db->select('*');
		$this->db->from(self::SUBSCRIPTIONS);
		$this->db->where('user_id',$user_id);
		$this->db->where('entry_variable',$entry_var); 
		$this->db->limit(1);
		$query = $this->db->get();
		if(!$query->result())
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	public function checkPlanExist($plan,$type)
	{
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::FREE_SUBSCRIPTIONS);
		$this->db->where('subscription_auth_level',$plan);
		$this->db->limit(1);
		$query = $this->db->get();
		$plan_info = $query->row_array();

		if($plan_info)
		{	
			return $plan_info;
			
		}
		else
		{
			return false;
		}
	}

}
