<?php

class PBReusableModel_Security extends CI_Model {

	const PARTNERS = 'auth_partners';
	const USER_TOKENS = 'users_auth_tokens';

    function __construct() {
        parent::__construct();
		$this->load->helper('date');
		$this->load->model('PBReusableModel_Global','globals');
    }

	function inititateParameterCheck($method) {

		if($method == "associateNotificationTokenWithUser") {
			$expected_post_parameters = array(
				"device_token"
			);
		}
		// $route['api/feed/videos/(:num)/limit/(:num)'] = 'MobileAPI/getVideosFeed/$1/$2';
		if($method == "checkUsersCurrentSubscription") {
			$expected_post_parameters = array();
		}
		if($method == "getArticleByID") {
			$expected_post_parameters = array();
		}
		if($method == "getPodcastByID") {
			$expected_post_parameters = array();
		}
		if($method == "getVideoByID") {
			$expected_post_parameters = array();
		}
		if($method == "getVideosFeedFromYoutube") {
			$expected_post_parameters = array();
		}
		if($method == "getVideosFeed") {
			$expected_post_parameters = array();
		}
		if($method == "getVideosFeedFromWordpress") {
			$expected_post_parameters = array();
		}
		if($method == "recordAnalyticPoint") {
			$expected_post_parameters = array(
				"type","variable","secondary_variable"
			);
		}
		if($method == "associateExistingAMemberAccountWithUser") {
			$expected_post_parameters = array(
				"amember_email","amember_password"
			);
		}
		if($method == "unlinkDeviceForUser") {
			$expected_post_parameters = array(
				"id"
			);
		}
		if($method == "getDevicesForUser") {
			$expected_post_parameters = array(
			);
		}
		if($method == "getOrdersForUser") {
			$expected_post_parameters = array(
			);
		}
		if($method == "creditUserAccount") {
			$expected_post_parameters = array(
				"value","title","entry_variable"
			);
		}
		if($method == "purchaseProduct") {
            $expected_post_parameters = array(
				"product_id"
            );
        }
		if($method == "getWalletForUser") {
            $expected_post_parameters = array(
            );
        }
		if($method == "getWritingFeed") {
            $expected_post_parameters = array(
            );
        }
		if($method == "getWritingFeedFromWordpress") {
            $expected_post_parameters = array(
            );
        }
		if($method == "getPodcastFeed") {
            $expected_post_parameters = array(
            );
        }
		if($method == "getPodcastFeedFromWordpress") {
            $expected_post_parameters = array(
            );
        }
		if($method == "getNotificationPreferencesForUser") {
            $expected_post_parameters = array(
            );
        }
		if($method == "updateNotificationPreferencesForUser") {
            $expected_post_parameters = array(
            );
        }
		if($method == "updateUsersEmail") {
            $expected_post_parameters = array(
				"new_email","old_email"
            );
        }
		if($method == "checkSubscriptionForUser") {
            $expected_post_parameters = array(
            );
        }
        if($method == "loginTheUser") {
            $expected_post_parameters = array(
            	"email","passwd","device_type",
            );
        }
		if($method == "logoutTheUser") {
            $expected_post_parameters = array(
            );
        }
		if($method == "registerTheUser") {
            $expected_post_parameters = array(
				"email","password","opt_in","firstname","lastname","username","country"
            );
        }
		if($method == "activateTheUser") {
            $expected_post_parameters = array(
				"activation_code","email",
            );
        }
		if($method == "recoverTheUser") {
            $expected_post_parameters = array(
				"email",
            );
        }
		if($method == "resetTheUsersPassword") {
            $expected_post_parameters = array(
				"recovery_code","email","password",
            );
        }
		if($method == "changeTheUsersPassword") {
            $expected_post_parameters = array(
				"old_password","new_password",
            );
        }
		if($method == "updateUsersDetails") {
            $expected_post_parameters = array(
				"firstname","lastname","username",
            );
        }
		if($method == "updateUsersAvatar") {
            $expected_post_parameters = array();
        }
		if($method == "checkIfEmailExists") {
            $expected_post_parameters = array(
				"email",
            );
        }
		if($method == "checkIfUsernameExists") {
            $expected_post_parameters = array(
				"username",
            );
        }
		if($method == "registerTheGuestUser") {
            $expected_post_parameters = array();
        }
		if($method == "convertTheGuestUserToFullAccount") {
            $expected_post_parameters = array(
				"email",
				"password",
				"opt_in",
				"firstname",
				"lastname",
				"username",
				"country",
            );
        }
		if($method == "hello_world") {
            $expected_post_parameters = array();
        }
		if($method == "resendActivationCode") {
            $expected_post_parameters = array(
				'email',
			);
        }
		if($method == "checkAuthCode") {
            $expected_post_parameters = array();
        }

        if (!$this->checkIfParameterIsAmbiguous($expected_post_parameters,$this->input->post())) { return false; }
        if (!$this->checkExpectedParametersForFunction($expected_post_parameters)) { return false; }

        return true;
    }

	function checkExpectedParametersForFunction($expected_parameters) {
		 // var_dump($this->input->post());
		foreach($expected_parameters as $parameter=>$p) {
			if (!$this->input->post($p)) {
				echo json_encode(array('success' => false, 'message' => 'An expected parameter is missing', 'expected' => $expected_parameters));
				return false;
			}
		}
		return true;
	}

    function checkIfParameterIsAmbiguous($expected_array, $given_array) {
		$continue = true;
		foreach ($given_array as $key => $value) {
			if (!in_array($key, $expected_array)) {
				$continue = false;
				if($key == 'device_token') {
					$continue = true;
				}
				if($key == 'value') {
					$continue = true;
				}
			}
		}
        if(!$continue) {
            echo json_encode(array('success' => false, 'message' => 'An unexpected parameter was included in the post body'));
        }
		return $continue;
	}

	public function generateToken($data){
		$partner_id = $data['partner_id'];
		$reason = $data['access_type'];
		$static_str='TAW';
		$currenttimeseconds = date("mdY_Hisu");
		$token_id=$static_str.$partner_id.$currenttimeseconds.microtime();
		$token_data = array(
			'api_token' => md5($token_id),
			'access_type' => $reason,
		);
        $this->load->database();
        $this->db->where('id', $partner_id);
		$this->db->update(self::PARTNERS, $token_data);
		$this->db->trans_complete();
		if ($this->db->trans_status() === TRUE) {
			return md5($token_id);
		} else {
			return false;
		}
	}

	public function countLinkedDevicesForUser($user_id) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USER_TOKENS);
		$this->db->where('user_id',$user_id);
		$this->db->where('active',1);
		$query = $this->db->get();
		if($query->num_rows()) {
			return $query->num_rows();
		} else {
			return false;
		}
	}

	public function checkIfDeviceIsAlreadyAssociatedWithUser($user_id,$identifier,$name) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USER_TOKENS);
		$this->db->where('user_id',$user_id);
		$this->db->where('unique_device_identifier',$identifier);
		$this->db->where('unique_device_name',$name);
		$query = $this->db->get();
		$row = $query->row_array();
		if($row) {
			// var_dump($row['user_auth_token']);
			return $row['user_auth_token'];
		} else {
			return false;
		}
	}

	public function checkIfDeviceAndTokenIsAlreadyAssociatedWithUser($user_id,$token,$identifier,$name) {
		$this->load->database();
		$this->db->select('*');
		$this->db->from(self::USER_TOKENS);
		$this->db->where('user_id',$user_id);
		$this->db->where('user_auth_token',$token);
		$this->db->where('unique_device_identifier',$identifier);
		$this->db->where('unique_device_name',$name);
		$query = $this->db->get();
		if($query->row_array()) {
			return true;
		} else {
			return false;
		}
	}

	public function generateMultipleTokens($data){

		$characters = 'ABCEFHJKMNPRTUVWXY493712568';
		$static_str='TAWUSER';

		$string_one = '';
		$string_two = '';
		$string_three = '';
		$string_four = '';
		$string_five = '';
		$partner_id = 3;

		for ($i = 0; $i < 6; $i++) {
		    $string_one .= $characters[rand(0, strlen($characters) - 1)];
		    $string_two .= $characters[rand(0, strlen($characters) - 1)];
		    $string_three .= $characters[rand(0, strlen($characters) - 1)];
		    $string_four .= $characters[rand(0, strlen($characters) - 1)];
		    $string_five .= $characters[rand(0, strlen($characters) - 1)];
		}

		$currenttimeseconds = date("mdY_Hisu");
		$token_id=$static_str.$partner_id.$currenttimeseconds.microtime().$string_one;

		// $currenttimeseconds = date("mdY_Hisu");
		$token_id_two=$static_str.$partner_id.$currenttimeseconds.microtime().$string_two;

		// $currenttimeseconds = date("mdY_Hisu");
		$token_id_three=$static_str.$partner_id.$currenttimeseconds.microtime().$string_three;

		// $currenttimeseconds = date("mdY_Hisu");
		$token_id_four=$static_str.$partner_id.$currenttimeseconds.microtime().$string_four;

		// $currenttimeseconds = date("mdY_Hisu");
		$token_id_five=$static_str.$partner_id.$currenttimeseconds.microtime().$string_five;

		// $static_str='SQUSER';
		// $currenttimeseconds = date("mdY_His");
		// $token_id=$static_str.$data['partner_id'].$currenttimeseconds;
		$token_data = array(
			'user_auth_token_one' => md5($token_id),
			'user_auth_token_two' => md5($token_id_two),
			'user_auth_token_three' => md5($token_id_three),
			'user_auth_token_four' => md5($token_id_four),
			'user_auth_token_five' => md5($token_id_five)
		);
		return $token_data;
	}


	public function generateUserToken($data){
		// var_dump($data);
		if(!isset($data['unique_device_identifier'])) {
			$data['unique_device_identifier'] = '';
		}
		if(!isset($data['unique_device_name'])) {
			$data['unique_device_name'] = '';
		}
		$characters = 'ABCEFHJKMNPRTUVWXY493712568';
		$string = '';
		for ($i = 0; $i < 6; $i++) {
		    $string .= $characters[rand(0, strlen($characters) - 1)];
		}
		$static_str='TAWUSER';
		$currenttimeseconds = date("mdY_Hisu");
		$token_id=$static_str.$data['partner_id'].$currenttimeseconds.microtime().$string;

		// $static_str='SQUSER';
		// $currenttimeseconds = date("mdY_His");
		// $token_id=$static_str.$data['partner_id'].$currenttimeseconds;
		$token_data = array(
			'user_auth_token' => md5($token_id),
			'partner_id' => $data['partner_id'],
			'user_id' => $data['user_id'],
			'user_agent' => $data['user_agent'],
			'host' => $data['host'],
			'unique_device_identifier' => $data['unique_device_identifier'],
			'unique_device_name' => $data['unique_device_name'],
			'last_logged_in' => date('Y-m-d H:i:s'),
		);
		$this->load->database();
		if ($this->db->insert(self::USER_TOKENS, $token_data)) {
			return md5($token_id);
		} else {
			return false;
		}
	}

	public function updateLastLoggedInDate($token) {
		$token_data = array(
			'last_logged_in' => date('Y-m-d H:i:s'),
		);
		$this->load->database();
		$this->db->where('user_auth_token', $token);
		$this->db->update(self::USER_TOKENS, $token_data);
		$this->db->trans_complete();
		if ($this->db->affected_rows() == '1') {
			return true;
		} else {
			return false;
		}
	}

	public function deactivateUserToken($token) {
		return true;
		// $token_data = array();
		// $token_data['user_auth_token'] = $token;
		// $token_data['active'] = 1;
		// $this->load->database();
		// $this->db->where('user_auth_token', $token);
		// $this->db->where('active', 1);
		// $this->db->update(self::USER_TOKENS, $token_data);
		// $this->db->trans_complete();
		// if ($this->db->affected_rows() == '1') {
		// 	return true;
		// } else {
		// 	return false;
		// }
		// $this->load->database();
		// $this->db->delete(self::USER_TOKENS, array('device_token' => $data));
		// return 1;

	}

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

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

	public function checkAuthenticationTokens($user_id,$app_token,$user_token) {
		$user_token_check = $this->checkIfExistingTokenIsActive($user_id,$user_token);
		if ($user_token_check) {
			$app_token_check = $this->isAppTokenValid($app_token);
			if ($app_token_check) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}
