<?php

class PBReusableModel_Subscriptions extends CI_Model {

    const FREE_SUBSCRIPTIONS = 'subscription_free_plan';

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

    public function create_new_invoice() {
        $url = 'https://www.theanfieldwrap.com/subscription/api/invoices';

        $vars = array(
            '_key' => 'coBP0xqoap3R1g6o7beS',
            // Invoice Record
            'public_id' => 'TRAX',
            'user_id' => 18260,
            'paysys_id' => 'offline',
            'currency' => 'GBP',
            'first_subtotal' => '22.00',
            'first_discount' => '0.00',
            'first_tax' => '0.00',
            'first_shipping' => '0.00',
            'first_total' => '22.00',
            'first_period' => '1m',
            'rebill_times' => 99999, // means until cancel
            'second_subtotal' => '22.00',
            'second_discount' => '0.00',
            'second_tax' => '0.00',
            'second_shipping' => '0.00',
            'second_total' => '22.00',
            'second_period' => '1m',
            'is_confirmed' => 1, // Must be 1
            'status' => 0, // 1 - paid 0 - pending check Invoice model
            'nested' => array(
                'invoice-items' => array(
                    // InvoiceItem record
                    array(
                        'invoice_public_id' => 'TRAX',
                        'item_id' => 7, // product_id here;
                        'item_type' => 'product',
                        'item_title' => 'Test Sub from API',
                        'item_description' => 'Description of item',
                        'qty' => 1,
                        'first_discount' => '0.00',
                        'first_price' => '22.00',
                        'first_tax' => '0.00',
                        'first_shipping' => '0.00',
                        'first_total' => '22.00',
                        'first_period' => '1m',
                        'rebill_times' => 99999,
                        'second_discount' => '0.00',
                        'second_tax' => '0.00',
                        'second_shipping' => '0.00',
                        'second_total' => '22.00',
                        'second_price' => '22.00',
                        'second_period' => '1m',
                        'currency' => 'GBP',
                        'billing_plan_id' => 7 // Billing plan within  product, check am_billing_plan table.
                    )
                ),
                'invoice-payments' => array(
                    // InvoicePayment record
                    array(
                        'invoice_public_id' => 'TRAX',
                        'user_id' => 18260,
                        'paysys_id' => 'offline',
                        'receipt_id' => 'test-receipt',
                        'transaction_id' => 'test-transaction',
                        'currency' => 'GBP',
                        'amount' => '22.00'
                    )
                ),
                'access' => array(
                    // Access record
                    array(
                        'invoice_public_id' => 'TRAX',
                        'user_id' => 18260,
                        'product_id' => 7,
                        'transaction_id' => "test-transaction",
                        'begin_date' => '2019-06-26',
                        'expire_date' => '2019-07-26'
                    )
                )
            ));

        //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($vars));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));
        //execute post
        $result = curl_exec($ch);
        var_dump($result);
        //close connection
        curl_close($ch);
    }
    public function 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.".";
		}
		return 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,
		),JSON_PRETTY_PRINT);
		exit;
    }

    public function front_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 = $_GET['sub'];
		$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.".";
		}
		return 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,
		),JSON_PRETTY_PRINT);
		exit;
    }

    public function updateFreeSubscription($duration,$type) {
        $sub_data = [
            'plan_duration' => $duration
        ];
        $this->load->database();
        $this->db->where('plan_type',$type);
        $this->db->update(self::FREE_SUBSCRIPTIONS,$sub_data);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
        
    }

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


}
