<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class Payment extends CI_Controller 
    {
         function  __construct(){
            parent::__construct();
            $this->load->library('paypal_lib');
            is_test();
            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(){
            echo "string";
           echo "<pre>";print_r(auth('discount_ss'));exit();
         }

         function success($slug,$account_slug){

            $data = array();
         	//get payment data from paypal url
         	$paypalInfo = $this->input->get();
            $settings = get_setting();
            $package_info = get_id_by_package_slug($account_slug); //get package info by slug
            $u_info = get_all_user_info_slug($slug); //get user info by id from paypal url
            $data_info = array(
            	'user_id' => $u_info['user_id'],
            	'account_type' =>$package_info['id'],
            	'price' => $paypalInfo["amt"],
            	'currency_code' => $paypalInfo["cc"],
            	'status' => $paypalInfo["st"],
            	'txn_id' => $paypalInfo["tx"],
                'payment_type' => 'paypal',
            	'created_at' => d_time(),
            );
            $insert = $this->common_m->insert($data_info,'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');

	            if($u_info['price'] = $paypalInfo["amt"]){

	            	$this->email_m->send_payment_paid_email($data_info,'Paypal'); // 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_info,'paypal');
                    endif;
	            	$data['status'] = 1;
	            	$data['msg'] = 'Paypal Payment Successfull';
	            }else{
	            	$data['msg'] = 'Paypal Payment failed';
	            	$data['status'] = 0;
	            }
	        endif;
            //pass the transaction data to view
            $data['main_content'] = $this->load->view('payment/payment_success', $data, TRUE);
            $this->load->view('payment_index',$data);
         }

         /*   Razorpay payment method
================================================== */
         function razorpay_payment_success(){
            $data = array();
            //get payment data from paypal url
            if (!empty($this->input->post('razorpay_payment_id'))) {



                $razorpay_payment_id = $this->input->post('razorpay_payment_id');
                $settings = get_setting();
                $package_info = get_package_info_by_id($this->input->post('product_id')); //get package info by id
                $u_info = get_all_user_info_slug($this->input->post('username')); //get user info by id from paypal url
              
                $amount = $this->input->post('totalAmount');

                $keys = array(
                    'key_id' => $settings['key_id'],
                    'secret_key' => $settings['razorpay_key'],
                );


                $data = array(
                    'amount' => $amount*100,
                    'currency' => get_currency('currency_code'),
                );


                $success = false;
                $error = '';
                try {                
                    $ch = $this->curl_handler($razorpay_payment_id, $data,$keys);
                    //execute post
                    $result = curl_exec($ch);

                    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                    if ($result === false) {
                        $success = false;
                        $error = 'Curl error: '.curl_error($ch);
                    } else {
                        $response_array = json_decode($result, true);
                            //Check success response
                        if ($http_status === 200 and isset($response_array['error']) === false) {
                            $success = true;
                        } else {
                            $success = false;
                            if (!empty($response_array['error']['code'])) {
                                $error = $response_array['error']['code'].':'.$response_array['error']['description'];
                            } else {
                                $error = 'RAZORPAY_ERROR:Invalid Response <br/>'.$result;
                            }
                        }
                    }
                    //close curl connection
                    curl_close($ch);
                } catch (Exception $e) {
                    $success = false;
                    $error = 'Request to Razorpay Failed';
                    echo json_encode(['st'=>0,'msg'=>$$error]);
                }

                if ($success === true) {
                    $payment_data = array(
                        'user_id' => $u_info['user_id'],
                        'account_type' => $package_info['id'],
                        'price' => $amount,
                        'currency_code' => $response_array['currency'],
                        'txn_id' => $this->input->post('razorpay_payment_id'),
                        'status' => $response_array['status'],
                        'payment_type' => 3,
                        'created_at' => d_time(),
                    );
                    $insert = $this->common_m->insert($payment_data,'payment_info');

                    $this->email_m->send_payment_paid_email($payment_data,'Razorpay');
                    if(isset($settings['admin_invoice']) && $settings['admin_invoice']==1):
                        $this->email_m->get_paid_invoice_to_admin($payment_data,'razorpay');
                    endif;
                    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');
                    echo json_encode(['st'=>1,'msg'=>'Payment Successfull']);

                } else {
                    $msg = 'Payment Canceled';
                    echo json_encode(['st'=>0,'msg'=>$msg]);
                }
            } else {
                $msg = 'An error occured. Contact site administrator, please!';
                echo json_encode(['st'=>0,'msg'=>$msg]);
                
            }

            //pass the transaction data to view
         }


         public function razorpay_seccess(){
            $data = array();
            $data['status'] = 1;
            $data['msg'] = 'Paypal Payment Successfull';
            $data['main_content'] = $this->load->view('payment/payment_success', $data, TRUE);
            $this->load->view('payment_index',$data);
         }

         
         //paypal payment cancel
         function cancel(){
         	$data['msg'] = 'Payment canceled';
	        $data['status'] = 0;
            $data['main_content'] = $this->load->view('payment/payment_success', $data, TRUE);
            $this->load->view('payment_index',$data);
         }
         
         private function curl_handler($payment_id, $data, $keys)  {
            $url            = 'https://api.razorpay.com/v1/payments/'.$payment_id.'/capture';
            $key_id         = $keys['key_id'];
            $key_secret     = $keys['secret_key'];
            $params = http_build_query($data);
                //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_id.':'.$key_secret);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            return $ch;
        }  
    
    public function payment_success($slug,$status=1)
    {
        $data = array();
        $data['page_title'] = "Payment";
        $data['slug'] = $slug;
        $data['status'] = $status;
        if($status==1):
            $data['msg'] = 'Payment Successfull';
        else:
            if(isset($_GET['msg'])){
                $data['msg']= $_GET['msg'];
            }else{
                $data['msg'] = '';
            };
            
        endif;
        if(isset($_GET['p'])){
            $data['payment_by']= $_GET['p'];
        }else{
            $data['payment_by'] = '';
        };

        $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_check($data){
            $package_info = get_package_info_by_id($data['package_id']); //get package info by slug
            $u_info = get_all_user_info_slug($data['username']); //get user info by id from paypal url
            $data_info = array(
                'user_id' => $u_info['user_id'],
                'account_type' =>$package_info['id'],
                'price' => $data["amount"],
                'currency_code' => $data["currency_code"],
                'status' => $data["status"],
                'txn_id' => $data["txn_id"],
                'payment_type' => 'flutterwave',
                'created_at' => d_time(),
            );
            $insert = $this->common_m->insert($data_info,'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');
            endif;

        redirect(base_url("payment/payment_success/{$u_info['username']}/1?msg={$msg}&p=flutterwave"));
    }

    public function flutterwave(){
        $this->load->library(['flutterwave_lib']);

        $data = array(
            'amount'=>$_POST['amount'],
            'username'=> $_POST['slug'],
            'customer_email' => $_POST['customer_email'],
            'currency' => $_POST['currency'],
            'redirect_url'=>base_url("payment/payment_status/?u={$_POST['slug']}&package_id={$_POST['package_id']}"),
            'package_id'=>$_POST['package_id'],
            'csrf_test_name' =>$this->security->get_csrf_hash(),
        );
        $this->response = $this->flutterwave_lib->create_payment($data);
        if(!empty($this->response) || $this->response != ''){
            $this->response = json_decode($this->response,1);
            if(isset($this->response['status']) && $this->response['status'] == 'success'){
                redirect($this->response['data']['link']);
            }else{
                redirect(base_url("payment/payment_success/{$u_info['username']}/0?msg={$this->response['message']}&p=flutterwave"));
            }
        }
    }


    public function payment_status()
    {
        $this->load->library(['flutterwave_lib']);
        $params = $this->input->get();
        $slug = $_GET['u'];
        $u_info = $this->common_m->get_user_info_by_slug($slug); //get user info by id from paypal url
       
        $id = get_id_by_slug($slug);
        $data['id']=$id;
        if(empty($id)){
            redirect(base_url('error-404'));
        }


        if(empty($params)){
            $data['status'] = 'error';
            $data['message'] = "No parameters found.";
            $this->load->view('payment_status',$data);
            
        }elseif(isset($params['txref']) && !empty($params['txref'])){
            $response = $this->flutterwave_lib->verify_transaction($params['txref']); 
            if(!empty($response)){
                $response = json_decode($response,1);
                if($response['status'] == 'success' && isset($response['data']['chargecode']) && ( $response['data']['chargecode'] == '00' || $response['data']['chargecode'] == '0') ){
                    
                    $data['package_id']    = $params['package_id'];
                    $data['customer_email']  = $response['data']['custemail'];
                    $data['username']         = $params['u'];
                    $data['txn_id']         = $response['data']['txref'];
                    $data['amount']         = $response['data']['amount'];
                    $data['currency_code']  = $response['data']['currency'];
                    $data['status']         = $response['data']['status'];
                    $data['message']        = $response['message'];
                    $data['full_data']      = $response;
                
                  $this->payment_check($data);
                }elseif( (isset($params['cancelled']) && $params['cancelled'] == true)){
                    $data['status'] = 'cancelled';
                    $data['message'] = 'Payment Cancelled by you or some other reasons. Try again!';
                    redirect(base_url("payment/payment_success/{$u_info['username']}/0?msg={$data['message']}&p=flutterwave"));
                }elseif( $response['status'] == 'error'){
                    $data['status'] = 'error';
                    $data['message'] = $response['message'];
                    redirect(base_url("payment/payment_success/{$u_info['username']}/0?msg={$data['message']}&p=flutterwave"));
                }
            }else{
                $data['status'] = 'error';
                $data['message'] = "No data returned from ";
                 redirect(base_url("payment/payment_success/{$u_info['username']}/0?msg={$data['message']}&p=flutterwave"));
            }
        }
    }




    public function mercado(){
        $settings = get_setting();
        $mercado = !empty($settings['mercado_config'])?json_decode($settings['mercado_config']):'';
         $package_info = get_package_info_by_slug($_GET['account_slug']); //get package info by slug
         $u_info = get_all_user_info_slug($_GET['slug']);
        $respuesta = array(
            'Payment' => $_GET['payment_id'],
            'Status' => $_GET['status'],
            'MerchantOrder' => $_GET['merchant_order_id']        
        ); 
        MercadoPago\SDK::setAccessToken($mercado->access_token);
        $merchant_order = $_GET['payment_id'];

        $payment = MercadoPago\Payment::find_by_id($merchant_order);
        $merchant_order = MercadoPago\MerchantOrder::find_by_id($payment->order->id);
       
        $data_info = array(
            'user_id' => $u_info['user_id'],
            'account_type' =>$package_info['id'],
            'price' => $payment->transaction_details->total_paid_amount,
            'currency_code' => $payment->currency_id,
            'status' => $payment->status,
            'txn_id' => $_GET['preference_id'],
            'payment_type' => 'mercadopago',
            'created_at' => d_time(),
            'all_info' => json_encode($merchant_order->payments),
        );
        $insert = $this->common_m->insert($data_info,'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');
        endif;
         redirect(base_url("payment/payment_success/{$_GET['slug']}/1?msg={$data['message']}&p=mercadopago"));
        exit();


        $paid_amount = 0;
        foreach ($merchant_order->payments as $payment) {   
            if ($payment['status'] == 'approved'){
                $paid_amount += $payment['transaction_amount'];
            }
        }
        echo "<pre>";print_r($merchant_order->payments);exit();
    // If the payment's transaction amount is equal (or bigger) than the merchant_order's amount you can release your items
        if($paid_amount >= $merchant_order->total_amount){
                if (count($merchant_order->shipments)>0) { // The merchant_order has shipments
                    if($merchant_order->shipments[0]->status == "ready_to_ship") {
                        print_r("Totally paid. Print the label and release your item.");
                    }
                } else { // The merchant_order don't has any shipments
                print_r("Totally paid. Release your item.");
            }
        } else {
            print_r("Not paid yet. Do not release your item.");
        }

        echo "<pre>";print_r($_GET);exit();


    }

    public function paytm_verify(){
        $package_info = get_package_info_by_slug($_GET['account_slug']); //get package info by slug
        $u_info = get_all_user_info_slug($_GET['slug']);
        $mkey = $_GET['key'];
        require_once("vendor/paytm/paytmchecksum/PaytmChecksum.php");
        $checksum = (!empty($_POST['CHECKSUMHASH'])) ? $_POST['CHECKSUMHASH'] : '';
        unset($_POST['CHECKSUMHASH']);
        $verifySignature = PaytmChecksum::verifySignature($_POST, $mkey, $checksum);
        if($verifySignature){
          
            $data_info = array(
                'user_id' => $u_info['user_id'],
                'account_type' =>$package_info['id'],
                'price' => $_POST['TXNAMOUNT'],
                'currency_code' => $_POST['CURRENCY'],
                'status' => $_POST['STATUS'],
                'txn_id' => $_POST['TXNID'],
                'payment_type' => 'paytm',
                'created_at' => d_time(),
                'all_info' => json_encode(['bank_name'=>$_POST['BANKNAME'],'bank_txn_id'=>$_POST['BANKTXNID'],'gateway'=>$_POST['GATEWAYNAME'],'payment_mode'=>$_POST['PAYMENTMODE']]),
            );
            $insert = $this->common_m->insert($data_info,'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');
            endif;
             redirect(base_url("payment/payment_success/{$_GET['slug']}/1?msg={$data['message']}&p=paytm"));

        }else{
            $data['status'] = 'error';
            $data['message'] = "No data returned from ";
            redirect(base_url("payment/payment_success/{$u_info['username']}/0?msg={$data['message']}&p=paytm"));
        }
    }


         
    }
?>