<?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");
header("Access-Control-Expose-Headers: content-disposition");
ini_set('memory_limit', '-1');

class SubscriptionsAPI extends MY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('PBReusableModel_Security','appsecurity');
		$this->load->model('PBReusableModel_Analytics','analytics');
		$this->load->model('PBReusableModel_Partners','partners');
		$this->load->model('PBReusableModel_Global','globals');
		$this->load->model('PBReusableModel_User','users');
		$this->load->model('PBReusableModel_Notifications','notifications');
		$this->load->model('PBReusableModel_CSVExport','csv');
		$this->load->model('PBReusableModel_Subscriptions','subscriptions');
		$this->load->model('Auth_Model', 'auth');
        $this->load->library("braintree_lib");
		$this->headers = $this->input->request_headers();

	}


    // Handle events sent from a webhooks via PayPal
    // Webhook: https://api-taw.pixelbeard.co/api/system/webhooks/paypal/events
    // Webhook ID: 9R508543NA136393B

    public function create_new_invoice() {
        $this->subscriptions->create_new_invoice();
    }

    public function api_associate_braintree_customer_id_with_user() {

    }

    public function api_find_customer() {
        var_dump($this->braintree_lib->api_find_customer($this->input->post('customer_id')));
    }
    public function api_update_customer() {
        var_dump($this->braintree_lib->api_update_customer($this->input->post('customer_id'),$this->input->post()));
    }


    public function api_create_customer() {
        $post_data = $this->input->post();
        $post_data['customFields'] = array(
            'taw_amember_user_id' => $this->input->post('taw_amember_user_id'),
            'taw_app_user_id' => $this->input->post('taw_app_user_id')
        );
        unset($post_data['taw_amember_user_id']);
        unset($post_data['taw_app_user_id']);
        // $customer = array(
        //     'firstName' => 'Will',
        //     'lastName' => 'Roberts',
        //     'email' => 'will+btt1@pixelbeard.co',
        //     'paymentMethodNonce' => '08d4ac03-a6e7-00e1-7314-ae9a4dce7c35',
        // );
        // $customer = array(
        //     'firstName' => $this->input->post('firstName'),
        //     'lastName' => $this->input->post('lastName'),
        //     'email' => $this->input->post('email'),
        // );
        var_dump($this->braintree_lib->createNewCustomer($post_data));
    }

    public function complete_checkout() {
        $this->braintree_lib->checkout_sub($this->input->post('amount'),$this->input->post('nonce'));
    }


    public function get_plans() {
        echo json_encode($this->braintree_lib->getAllPlans());
    }

	public function testPurchase() {
		$this->braintree_lib->testPurchase($this->input->post());
	}

	public function createClientToken() {
		$paypal_gateway = $this->braintree_lib->createClientToken();

	}
	public function createNewCustomer() {
		$this->braintree_lib->createNewCustomer();
	}

    public function helloBraintree() {
		$token = $this->braintree_lib->create_client_token();
        echo json_encode(array(
            'success' => true,
            'message' => 'Connection to Braintree is good!',
            'context' => 'The connection to Braintree is working and ready to go',
			'token' => $token,
			// 'paypal' => $paypal
        ));
    }

    public function handlePayPalEvent() {
        echo json_encode(array(
            'success' => true,
            'message' => 'PayPal event received!',
            'context' => 'The Admin API is working and ready to go'
        ));
    }

    /* ********************************************************** */
	/* SUBSCRIPTION MANAGER ************************************* */
	/* ********************************************************** */

	// will-facilitator@pixelbeard.co
	// Ae25ezYgJkSaXHv0OrVLfpeLtFFxMqwtwa4fQfynvis73Rz90bJ5CnGF1DkdswPYsERHHsMue_pX98A4
	// EKsOl4bMNZKL91vysVdN3_EoTlZRWpZSpOywtqW2cFNxYwWXQCLfJHD2LiX5m--qP-q_joiNVsP1kh2U

	function api_get_sub_info() {

		echo $this->subscriptions->api_get_sub_info();

		// $user = $this->users->getFullUserByTokenFrontend('06072b0536fda3846569d8ce07e09456');
		// $user = $this->users->getUserObject($user['email']);
		//
		// // $user = $this->checkUsersCurrentSubscription();
		// $sorted_array = $this->globals->sortArrayByKey($user['subscriptions'],'subscription_auth_level',SORT_DESC);
		// $sub_to_match_against = $sorted_array[0];
		//
		// $current_level = $sub_to_match_against['subscription_auth_level'];
		// $new_level = $this->input->post('new_sub_id');
		// $renew_date = $sub_to_match_against['subscription_expiry'];
		//
		// $date = DateTime::createFromFormat("Y-m-d", $renew_date);
		// $day = $date->format("d");
		// $month = $date->format("m");
		// $year = $date->format("Y");
		//
		// $subscription_start_date = "";
		// $next_billing_date = "";
		// $billing_info = "";
		//
		// $current_subscription = "";
		// $new_subscription = "";
		//
		// $subscriptions = $this->braintree_lib->getAllPlansNoUserData();
		// foreach($subscriptions['subscriptions'] as $subscription) {
		// 	if($subscription['id'] == $new_level) {
		// 		$new_subscription = $subscription;
		// 	}
		// 	if($subscription['id'] == $current_level) {
		// 		$current_subscription = $subscription;
		// 	}
		// }
		//
		// // Check if user is upgrading or downgrading
		// $upgrading = ($sub_to_match_against['subscription_auth_level'] > $this->input->post('new_sub_id') ? false : true);
		// if($upgrading) {
		// 	$subscription_start_date = (new \DateTime())->format('d-m-Y');
		// 	$next_billing_date = $date->format('d-m-Y');
		// 	$billing_info = "Your new subscription will start immediately but we will start billing you for this on your next renewal date which is currently ".$next_billing_date.". ";
		// } else {
		// 	$subscription_start_date = $date->format('d-m-Y');
		// 	$next_billing_date = $date->format('d-m-Y');
		// 	$billing_info = "Your current subscription will end and your new subscription will start on ".$next_billing_date.".";
		// }
		// echo json_encode(array(
		// 	'success' => true,
		// 	'current_subscription_level' => $current_level,
		// 	'current_subscription_details' => $current_subscription,
		// 	'new_subscription_level' => $new_level,
		// 	'new_subscription_details' => $new_subscription,
		// 	'user_is_upgrading' => $upgrading,
		// 	'new_subscription_start_date' => $subscription_start_date,
		// 	'new_subscription_billing_date' => $next_billing_date,
		// 	'new_subscription_info' => $billing_info,
		// ));
		// exit;
	}

	function checkUsersCurrentSubscription() {
		if ($this->globals->checkUserToken($this->headers)) {
			// var_dump($this->headers);
			$user = $this->users->getFullUserByTokenFrontend($this->headers['User-Api-Token']);
			$subs = $this->users->getUserSubscriptionsForAMember($user['user_id']);
			$sub_array = array();
			$has_one = false;
			$has_seven = false;
			$has_eight = false;
			$has_nine = false;
			foreach($subs as $sub) {
				if($sub->subscription_auth_level == 1) {
					$has_one = true;
				}
				if($sub->subscription_auth_level == 7) {
					$has_seven = true;
				}
				if($sub->subscription_auth_level == 8) {
					$has_eight = true;
				}
				if($sub->subscription_auth_level == 9) {
					$has_nine = true;
				}
			}
			$sub_data = array();
			if($has_one && !$has_seven && !$has_eight && !$has_nine) {
				// Skeleton
				$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
				$sub_data['subscription_expiry'] = $sub->subscription_expiry;
			} else if($has_seven && !$has_one && !$has_eight && !$has_nine) {
				// Video
				$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
				$sub_data['subscription_expiry'] = $sub->subscription_expiry;
			} else if($has_eight && !$has_one && !$has_seven && !$has_nine) {
				// Audio
				$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
				$sub_data['subscription_expiry'] = $sub->subscription_expiry;
			} else if($has_nine && !$has_seven && !$has_eight && !$has_one) {
				// Premium
				$sub_data['subscription_auth_level'] = $sub->subscription_auth_level;
				$sub_data['subscription_expiry'] = $sub->subscription_expiry;
			} else if(count($sub_array)>1) {
				// More than one
				if($has_nine) {
					array_push($sub_array,$sub_data);
					$user_array['subscriptions'] = $sub_array;
					echo json_encode(array(
						'success' => true,
						'subs' => $subs,
						'user' => $user
					));
					exit;
				} else if($has_eight) {
					array_push($sub_array,$sub_data);
					$user_array['subscriptions'] = $sub_array;
					echo json_encode(array(
						'success' => true,
						'subs' => $subs,
						'user' => $user
					));
					exit;
				} else if($has_seven) {
					array_push($sub_array,$sub_data);
					$user_array['subscriptions'] = $sub_array;
					echo json_encode(array(
						'success' => true,
						'subs' => $subs,
						'user' => $user
					));
					exit;
				} else if($has_one) {
					array_push($sub_array,$sub_data);
					$user_array['subscriptions'] = $sub_array;
					echo json_encode(array(
						'success' => true,
						'subs' => $subs,
						'user' => $user
					));
					exit;
				} else {
					$user_array['subscriptions'] = $sub_array;
					echo json_encode(array(
						'success' => true,
						'subs' => $subs,
						'user' => $user
					));
				}
			}


		}
	}

	function getFreeSubscriptions()
	{
		$headers = $this->input->request_headers();
		if($this->checkToken($headers))
		{
			$free_subscription = $this->subscriptions->getFreeSubscription();
			if($free_subscription)
			{
				echo json_encode(array(
					'success' => true,
					'message' => 'List of Free Subscriptions',
					'free_susbscriptions' => $free_subscription

				));
			}
			else
			{
				echo json_encode(array(
					'success' => false,
					'message' => 'Free subscriptions are not available'

				));

			}
		}

	}

	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'));
		}
	}

	function activateUserSubscription() {
		if ($this->globals->checkUserToken($this->headers)) {
			if(!$this->input->post('subscription_plan'))
			{
				echo json_encode(array(
					'success' => false,
					'message' => 'Expected parameter subscription_plan missing'
	
				));
				return ;
			}

			if(!$this->input->post('subscription_type'))
			{
				echo json_encode(array(
					'success' => false,
					'message' => 'Expected parameter subscription_type missing'
	
				));
				return ;
			}

			if($this->input->post('subscription_days') || $this->input->post('subscription_expiry'))
			{
				if($this->input->post('subscription_days') && !is_numeric($this->input->post('subscription_days')))
				{
					echo json_encode(array(
						'success' => false,
						'message' => 'Days should be numeric only'
		
					));
					return ;
				}

				if ($this->input->post('subscription_expiry') && !preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$this->input->post('subscription_expiry'))) {
					echo json_encode(array(
						'success' => false,
						'message' => 'Expiry date should be in yyyy-mm-dd format'
		
					));
					return ;
				} 
			}
			else
			{
				echo json_encode(array(
					'success' => false,
					'message' => 'Expected parameter subscription_days or subscription_expiry missing'
	
				));
				return ;
			}

			if($this->input->post('entry_variable'))
			{
				$entry_variable = $this->input->post('entry_variable');
			}
			else{
				$entry_variable = 0;
			}


			$user_subscription = [
				'plan' => $this->input->post('subscription_plan'),
				'type' => $this->input->post('subscription_type'),
				'days' => $this->input->post('subscription_days')?$this->input->post('subscription_days'):'',
				'expiry' => $this->input->post('subscription_expiry')?$this->input->post('subscription_expiry'):'',
				'user-api-token' => $this->headers['User-Api-Token'],
				'entry_variable' => $entry_variable

			];
			
			if($this->input->post('subscription_type')=='free')
			{
				$new_user = $this->users->checkNewUser($this->headers['User-Api-Token']);

				if($new_user)
				{
					$activate = $this->users->activateFreeSubscriptionForUser($new_user,$user_subscription);
					if($activate){
						echo json_encode(array(
							'success' => true,
							'message' => 'Free Subscription activated successfully',
							'user' => $activate
			
						));
					}
					else
					{
						echo json_encode(array(
							'success' => false,
							'message' => 'Subscription plan not exist'
						));
					}

				}
				else
				{
					echo json_encode(array(
						'success' => true,
						'message' => 'Only new users are validated for free subscription'
		
					));
				}
			}
			elseif($this->input->post('subscription_type')=='paid')
			{
				$activate = $this->users->activatePaidSubscriptionForUser($user_subscription);
				if($activate){
					echo json_encode(array(
						'success' => true,
						'message' => 'Subscription activated successfully',
						'user' => $activate
		
					));
				}
				else
				{
					echo json_encode(array(
						'success' => false,
						'message' => 'Invalid Subscription'
					));
				}
			}
			else
			{
				echo json_encode(array(
					'success' => false,
					'message' => 'Invalid Request'
				));
			}
			
		}
	}
}
