<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Stripe extends CI_Controller {
	public function __construct(){
		parent::__construct();
        $this->config->load('stripe_config');
        if(d_auth('is_discount')==TRUE){
        	$this->id = !empty(d_auth('coupon_id'))?d_auth('coupon_id'):0;
        }else{
        	$this->id = 0;
        }
	}
	

	public function index($slug,$account_slug)
	{
		$data = array();
		$data['page_title'] = "Stripe Payment";
		$data['slug'] = $slug;
		if(empty($slug)){
			redirect(base_url('404'));
		}
		$data['package'] = $this->admin_m->get_id_by_package_slug($account_slug);
		$data['u_info'] = get_all_user_info_slug($slug);
		$data['main_content'] = $this->load->view('payment/stripe_payment_form', $data, TRUE);
		$this->load->view('payment_index',$data);
		
	}


	public function stripe_success($slug,$status=1)
	{
		$data = array();
		$data['page_title'] = "Stripe Payment";
		$data['slug'] = $slug;
		$data['status'] = $status;
		if($status==1):
			$data['msg'] = 'Stripe Payment Successfull';
		else:
			$data['msg'] = 'Stripe Payment failed';
		endif;
		$data['u_info'] = get_all_user_info_slug($slug);
		$data['main_content'] = $this->load->view('payment/payment_success', $data, TRUE);
		$this->load->view('payment_index',$data);
		
	}





	public function payment()
	{
		is_test();
		if(!empty($this->input->post('stripeToken'))) {                                                             
            $amount = $this->input->post('amount');
            $package_id = $this->input->post('package_id');
            $username = $this->input->post('username');
            $name = $this->input->post('stripe_name');
            $email = $this->input->post('stripe_email');

            $u_info = get_all_user_info_slug($username);
            $package_info = $this->admin_m->get_package_info_by_id($package_id);
            $settings = get_setting();

            $params = array(
                'amount' => $amount * 100,
                'currency' => get_currency('currency_code'),
                'description' => 'Charge for '.$settings['site_name'].' Registrations',
                'source' => $this->input->post('stripeToken'),
                'metadata' => array( 
                	'product_id' => $package_id,
                )
            );
            $jsonData = $this->get_curl_handle($params);
            $resultJson = json_decode($jsonData, true);
            if($resultJson['amount_refunded'] == 0 && empty($resultJson['failure_code']) && $resultJson['paid'] == 1 && $resultJson['captured'] == 1){ 
            // Order details  
            $transactionID = $resultJson['balance_transaction']; 
            $currency = $resultJson['currency']; 
            $payment_status = $resultJson['status'];


             // If the order is successful 
            if($payment_status == 'succeeded') { 
          
			   $data = array(
			   		'user_id' => $u_info['user_id'],
			   		'account_type' => $package_info['id'],
			   		'price' => $amount,
			   		'currency_code' => $currency,
			   		'txn_id' => $transactionID,
			   		'status' => $payment_status,
			   		'payment_type' => 2,
			   		'created_at' => d_time(),
			   );
	   			$insert = $this->common_m->insert($data,'payment_info');
		   		if($insert):  
		   			if($this->id){
	                    $this->admin_m->update_discount($this->id);
	                }
			   		$this->common_m->update(array('is_verify'=>1,'is_payment'=>1,'is_expired'=>0,'start_date'=>d_time(),'end_date'=>add_year($package_info['type']),'account_type'=>$package_info['id'],'is_request'=>0),$u_info['user_id'],'users');

			        $this->email_m->send_payment_paid_email($data,'Credit Card'); // send payment transaction succesfull mail with transaction id

				    if(isset($settings['admin_invoice']) && $settings['admin_invoice']==1):
			        	$this->email_m->get_paid_invoice_to_admin($data,'Credit Card');
			        endif;
		            redirect(base_url('stripe-payment-success/'.$u_info['username'].'/1'));
		    	endif;
    		}else{
    			$this->session->set_flashdata('error','Payment Faild');
    			redirect(base_url('stripe-payment-success/'.$u_info['username'].'/0'));
    		}
		}else{
			$this->session->set_flashdata('error',$resultJson['message']);
			redirect(base_url('stripe-payment-success/'.$u_info['username'].'/0'));
		} //enter stripe
	}
}

// get curl handle method
    private function get_curl_handle($data) {
        $url = 'https://api.stripe.com/v1/charges';
        $key_secret = $this->config->item('stripe_secret');
        //cURL Request
        $ch = curl_init();
        //set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERPWD, $key_secret);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POST, 1);
        $params = http_build_query($data);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        $output = curl_exec ($ch);
        return $output;
    }

	public function offline_payment($slug,$account_slug)
	{
		is_test();
		$data = array();
		$data['page_title'] = "Offline Payment";
		$data['slug'] = $slug;
		$txn_id = 'op-'.random_string('alnum',4).'-'.random_string('numeric',4);
		$send = $this->email_m->offline_payment_request_mail($slug,$account_slug,$txn_id);
		$u_info = get_all_user_info_slug($slug);
		if($send){
			$u_info = get_all_user_info_slug($slug);
        	$package_info = get_id_by_package_slug($account_slug);
        	$off_data = array(
        		'txn_id' => $txn_id,
        		'username' => $slug,
        		'user_id' => $u_info['user_id'],
        		'email' => $u_info['email'],
        		'package' => $package_info['type_name'],
        		'price' => $package_info['price'],
        		'status' => 0,
        		'created_at' => d_time(),
        	); 
        	$this->admin_m->insert($off_data,'offline_payment');


        	$user_data = array(
        		'is_request' =>1,
        		'is_payment' =>0,
        		'account_type' =>$package_info['id'],
        	);
        	$this->admin_m->update($user_data,$u_info['user_id'],'users');

			$data['status'] = 1;
			$data['msg'] = 'Offline payment request send successfully';
		}else{
			$data['status'] = 0;
			$data['msg'] = 'Somethings Were Wrong!! Try again ';
		}
		$data['u_info'] = get_all_user_info_slug($slug);
		$data['main_content'] = $this->load->view('payment/payment_success', $data, TRUE);
		$this->load->view('payment_index',$data);
	}

}

