<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Ssl_payment
 *
 * @author Tania Chowdhary
 */
class Ssl_payment extends CI_Controller {

    //put your code here
    public function __construct() {
        parent::__construct();
        $this->load->model('Ssl_payment_model');
    }

    public function pay_invoice($temp_invoice_id) {

        $random_info = $this->random_number_model->set_temp_random_id($temp_invoice_id)->process()->get_info();

        // if does not matched random ID into database
        if (empty($random_info)) {
            redirect();
        }

        // assign data for view Invoice
        $data = $this->get_data_for_single_invoice($temp_invoice_id);

        // check paid amount data for view invoice
        $payment_data = $this->check_paid_amount_data_for_single_invoice($data);

        // get currency type if paid any payment
        $payment_data['currency_info'] = $this->invoice_payment_model->set_currency_info()->get_result();

        // mearge invoice information and payment data
        $merge_data = array_merge($data, $payment_data);
//        echo '<pre>';
//        print_r($merge_data);
//        $person_first_name=$merge_data['person_info']->person_first_name;
//        $total_amount=$merge_data['total_price'];
//        
//        echo $person_first_name.'------------'.$total_amount;
//        exit();
        /* PHP */
        $post_data = array();
        $post_data['store_id'] = "talhatraining001live";
        $post_data['store_passwd'] = "talhatraining001live27101";
        $post_data['total_amount'] = $merge_data['total_price'];
        $post_data['currency'] = "BDT";
        $post_data['tran_id'] = "SSLCZ_TEST_" . uniqid();
        $post_data['success_url'] = "https://talhatraining.com/success.php";
        $post_data['fail_url'] = "https://talhatraining.com/fail.php";
        $post_data['cancel_url'] = "https://talhatraining.com/cancel.php";

# EMI INFO
        $post_data['emi_option'] = "1";
        $post_data['emi_max_inst_option'] = "9";
        $post_data['emi_selected_inst'] = "9";

# CUSTOMER INFORMATION
        $post_data['cus_name'] = $merge_data['person_info']->person_first_name.' '.$merge_data['person_info']->person_last_name;
        $post_data['cus_email'] = $merge_data['person_info']->person_email;
        $post_data['cus_add1'] = $merge_data['person_info']->person_address;
        $post_data['cus_add2'] = $merge_data['person_info']->person_address;
        $post_data['cus_city'] = $merge_data['person_info']->person_city;
        $post_data['cus_state'] = $merge_data['person_info']->person_city;
        $post_data['cus_postcode'] = $merge_data['person_info']->person_zip;
        $post_data['cus_country'] = $merge_data['person_info']->person_country;
        $post_data['cus_phone'] =$merge_data['person_info']->person_contact_number;
        $post_data['cus_fax'] = "";

# SHIPMENT INFORMATION
        $post_data['ship_name'] = $merge_data['person_info']->person_first_name.' '.$merge_data['person_info']->person_last_name;
        $post_data['ship_add1 '] = $merge_data['person_info']->person_address;
        $post_data['ship_add2'] = $merge_data['person_info']->person_address;
        $post_data['ship_city'] = $merge_data['person_info']->person_city;
        $post_data['ship_state'] = $merge_data['person_info']->person_city;
        $post_data['ship_postcode'] =  $merge_data['person_info']->person_zip;
        $post_data['ship_country'] = $merge_data['person_info']->person_country;

# OPTIONAL PARAMETERS
//        $post_data['value_a'] = "ref001";
//        $post_data['value_b '] = "ref002";
//        $post_data['value_c'] = "ref003";
//        $post_data['value_d'] = "ref004";

        $post_data['value_a'] = "";
        $post_data['value_b '] = "";
        $post_data['value_c'] = "";
        $post_data['value_d'] = "";

# REQUEST SEND TO SSLCOMMERZ
        $direct_api_url = "https://securepay.sslcommerz.com/gwprocess/v3/api.php";

        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $direct_api_url);
        curl_setopt($handle, CURLOPT_TIMEOUT, 10);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($handle, CURLOPT_POST, 1);
        curl_setopt($handle, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);


        $content = curl_exec($handle);

        $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);

# PARSE THE JSON RESPONSE

        if ($code == 200 && !( curl_errno($handle))) {

            curl_close($handle);

            $sslcommerzResponse = $content;

            # PARSE THE JSON RESPONSE 

            $sslcz = json_decode($sslcommerzResponse, true);

//        echo '<pre>';
//        print_r($sslcz);
//        exit();

            if (isset($sslcz['status']) && $sslcz['status'] == 'SUCCESS') {

                if (isset($sslcz['GatewayPageURL']) && $sslcz['GatewayPageURL'] != '') {

                    echo '<meta http-equiv="refresh" content="0; url=' . $sslcz['GatewayPageURL'] . '" />';

                    #header("Location: " . $sslcz['GatewayPageURL']);

                    exit;
                } else {

                    echo "No redirect URL found!";
                }
            } else {

                echo "Invalid Credential!";
            }
        } else {

            curl_close($handle);

            echo "FAILED TO CONNECT WITH SSLCOMMERZ API";

            exit;
        }

        if (isset($_POST['val_id'])) {

            # FUNCTION TO CHECK HASH VALUE

            function _SSLCOMMERZ_hash_varify($store_passwd = "") {

                if (isset($_POST) && isset($_POST['verify_sign']) && isset($_POST['verify_key'])) {

                    # NEW ARRAY DECLARED TO TAKE VALUE OF ALL POST

                    $pre_define_key = explode(',', $_POST['verify_key']);

                    $new_data = array();

                    if (!empty($pre_define_key)) {

                        foreach ($pre_define_key as $value) {

                            if (isset($_POST[$value])) {

                                $new_data[$value] = ($_POST[$value]);
                            }
                        }
                    }

                    # ADD MD5 OF STORE PASSWORD

                    $new_data['store_passwd'] = md5($store_passwd);

                    # SORT THE KEY AS BEFORE

                    ksort($new_data);

                    $hash_string = "";

                    foreach ($new_data as $key => $value) {
                        $hash_string .= $key . '=' . ($value) . '&';
                    }

                    $hash_string = rtrim($hash_string, '&');

                    if (md5($hash_string) == $_POST['verify_sign']) {

                        return true;
                    } else {

                        return false;
                    }
                } else
                    return false;
            }

            # CALL THE FUNCTION TO CHECK THE RESUKT

            if (_SSLCOMMERZ_hash_varify(STORE_PASSWORD)) {

                $val_id = urlencode($_POST['val_id']);

                $store_id = urlencode(STORE_ID);

                $store_passwd = urlencode(STORE_PASSWORD);

                $requested_url = (SSLCZ_VALIDATION_API . "?val_id=" . $val_id . "&store_id=" . $store_id . "&store_passwd=" . $store_passwd . "&v=1&format=json");

                $handle = curl_init();

                curl_setopt($handle, CURLOPT_URL, $requested_url);

                curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);

                /* ---------- **Below two lines only for Localhost ----------- */
                curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);


                $result = curl_exec($handle);

                $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);

                if ($code == 200 && !( curl_errno($handle))) {

                    # TO CONVERT AS ARRAY
                    # $result = json_decode($result, true);
                    # $status = $result['status'];	
                    # TO CONVERT AS OBJECT

                    $result = json_decode($result, true);
//            echo'<pre>';
//            print_r($result);
//            exit();
                    # TRANSACTION INFO
//            $status = $result->status;
//            $tran_date = $result->tran_date;
//            $tran_id = $result->tran_id;
//            $val_id = $result->val_id;
//            $amount = $result->amount;
//            $store_amount = $result->store_amount;
//            $bank_tran_id = $result->bank_tran_id;
//            $card_type = $result->card_type;
//			
//		
//
//            # ISSUER INFO
//
//            $card_no = $result->card_no;
//            $card_issuer = $result->card_issuer;
//            $card_brand = $result->card_brand;
//            $card_issuer_country = $result->card_issuer_country;
//            $card_issuer_country_code = $result->card_issuer_country_code;

                    $pdata = array();
                    $pdata['status'] = $result['status'];
                    $pdata['tran_date'] = $result['tran_date'];
                    $pdata['tran_id'] = $result['tran_id'];
                    $pdata['val_id'] = $result['val_id'];
                    $pdata['amount'] = $result['amount'];
                    $pdata['store_amount'] = $result['store_amount'];
                    $pdata['bank_tran_id'] = $result['bank_tran_id'];
                    $pdata['card_type'] = $result['card_type'];
                    $pdata['card_no'] = $result['card_no'];
                    $pdata['currency'] = $result['currency'];
                    $pdata['card_issuer'] = $result['card_issuer'];
                    $pdata['card_brand'] = $result['card_brand'];
                    $pdata['card_issuer_country'] = $result['card_issuer_country'];
                    $pdata['card_issuer_country_code'] = $result['card_issuer_country_code'];
                    $pdata['currency_type'] = $result['currency_type'];
                    $pdata['currency_amount'] = $result['currency_amount'];
                    $pdata['varify_sign'] = $result['varify_sign'];
                    $pdata['verify_key'] = $result['verify_key'];
                    $pdata['risk_level'] = $result['risk_level'];
                    $pdata['risk_title'] = $result['risk_title'];


                    $this->Ssl_payment_model->save_ssl_payment_info($pdata);

                    # API AUTHENTICATION
//            $APIConnect = $result->APIConnect;
//            $validated_on = $result->validated_on;
//            $gw_version = $result->gw_version;
                } else {

                    echo "Failed to connect with SSLCOMMERZ";
                }
            } else {

                echo "Hash validation failed.";
            }
        }
        /*
          if ($status == "VALID") {

          /* echo '<pre>';
          print_r($_POST);
          print_r($_SESSION);
          print_r($_POST);
          echo '</pre>';
          die('JJJJJJJJJJJJJJJJJJ'); */

        # SAVE THIS DONATION IN DATABASE
        /*

          if ($_POST['tran_id'] == $_SESSION['SSLCZ_TRX_ID']) {

          $pdata=array();
          $pdata['status']=$_POST['status'];
          $pdata['tran_date']=$_POST['tran_date'];
          $pdata['tran_id']=$_POST['tran_id'];
          $pdata['val_id']=$_POST['val_id'];
          $pdata['amount']=$_POST['amount'];
          $pdata['store_amount']=$_POST['store_amount'];
          $pdata['bank_tran_id']=$_POST['bank_tran_id'];
          $pdata['card_type']=$_POST['card_type'];
          $pdata['card_no']=$_POST['card_no'];
          $pdata['currency']=$_POST['currency'];
          $pdata['card_issuer']=$_POST['card_issuer'];
          $pdata['card_brand']=$_POST['card_brand'];
          $pdata['card_issuer_country']=$_POST['card_issuer_country'];
          $pdata['card_issuer_country_code']=$_POST['card_issuer_country_code'];
          $pdata['currency_type']=$_POST['currency_type'];
          $pdata['currency_amount']=$_POST['currency_amount'];
          $pdata['varify_sign']=$_POST['varify_sign'];
          $pdata['verify_key']=$_POST['verify_key'];
          $pdata['risk_level']=$_POST['risk_level'];
          $pdata['risk_title']=$_POST['risk_title'];
          $pdata['status']=$_POST['status'];

          $this->Ssl_payment_model->save_ssl_payment_info($pdata);


          }
          } */
    }

    function get_data_for_single_invoice($temp_invoice_id) {
        $data = [];
        $data['invoice_id'] = $temp_invoice_id;
        $data['invoice_number'] = "tt-$temp_invoice_id";

        // get invoice information by invoice ID
        $data['invoice_info'] = $this->utility_model
                ->get_table_information('*', 'tbl_invoice', ['invoice_id' => $this->random_number_model->get_info()->random_type_id]);

        // get payment information by payment information ID
        $data['payment_info'] = $this->payment_model->set_payment_id($data['invoice_info']->payment_id)->set_info()->get_info();

        // check acces validation for view invoice
        $this->access_validation_for_single_invoice($data);

        // get all bank information
        $data['all_bank'] = $this->admin_payment_model->get_all_bank();

        // get payment person information
        $data['person_info'] = $this->utility_model
                ->get_table_information('*', 'tbl_person', ['person_id' => $data['payment_info']->person_id]);
        // get payment invoice information
        $data['payment_invoice_info'] = $this->utility_model
                ->get_table_information('*', 'tbl_invoice_payment', ['invoice_id' => $data['invoice_info']->invoice_id]);

        // get refund payment data
        $data['refund_payment_info'] = $this->utility_model
                ->get_table_information('payment_refund_amount', 'tbl_payment_refund', ['payment_refund_id' => $data['invoice_info']->payment_id]);
        return $data;
    }

    function check_paid_amount_data_for_single_invoice($data) {
        // get paid amount using payment ID
        $paid_amount = $this->payment_model->generate_paid_amount()->get_total_paid_amount();
        // if paid amount not equal zer0
        if (!empty($paid_amount)) {
            // get payment currency type
            $data['currency_type'] = $this->invoice_payment_model->get_currency_type();
            // generate country code
            $country_code = ($data['currency_type'] == 1) ? 'BD' : 'BB';
            // generate all payment amount
            return $this->payment_model->set_country_code($country_code)->set_currency($data['currency_type'])
                            ->generate_invoice_payment_amount()->get_payment_amount();
        } else {
            // get currency
            $currency = ($data['person_info']->person_country == 'BD') ? 1 : 2;
            // generate all payment amount
            return $this->payment_model->set_country_code($data['person_info']->person_country)->set_currency($currency)
                            ->generate_invoice_payment_amount()->get_payment_amount();
        }
    }

    /**
     * @Description         : check acces validation for view invoice 
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 12-12-2016 05:16 PM   
     * */
    function access_validation_for_single_invoice($data) {
        switch ($data['payment_info']->payment_type) {
            case 1: // for course
                // get course creator ID and resource person ID for check authentication
                $person_id = $this->course_model
                        ->set_course_id($data['payment_info']->payment_type_id)
                        ->get_person_id_for_course_view_invoice();
                break;

            case 2: // for Video Course
                $person_id = [0 => $this->session->person_id];
                break;
        }

        // course/video course creator/resource person access this course
        if (!in_array($this->session->person_id, $person_id)) {
            // if other user acces to this invoice then redirect home page
            if ($data['payment_info']->person_id != $this->session->person_id) {
                redirect();
            }
        }
    }

}
