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

use PlatiOnline\PO5 as PO5;

class Plati_online{

    public function __construct() {
        $this->ci =& get_instance();

        require_once APPPATH."libraries/po/PlatiOnline/PO5.php";
    }

    public function split_name($name) {
        $name = trim($name);
        $last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
        $first_name = trim( preg_replace('#'.preg_quote($last_name,'#').'#', '', $name ) );
        return array($first_name, $last_name);
    }

    function gateway($data)
    {
        //split full name
        /*$full_name = (isset($data['order']['bill_full_name']) && $data['order']['bill_full_name'])? $data['order']['bill_full_name']:'';
        $info_name = $this->split_name($full_name);
        $first_name = (isset($info_name[0]) && $info_name[0])? $info_name[0]:'';
        $last_name  = (isset($info_name[1]) && $info_name[1])? $info_name[1]:'';
        */

        $first_name = (isset($data['order']['bill_first_name']) && $data['order']['bill_first_name'])? $data['order']['bill_first_name']:'';
        $last_name = (isset($data['order']['bill_last_name']) && $data['order']['bill_last_name'])? $data['order']['bill_last_name']:'';

        if($first_name == '' OR $last_name == ''){
            $data['au'] = Globals::authenticatedMember();
            $first_name = (isset($data['au']['firstName']) && $data['au']['firstName'])? $data['au']['firstName']:'';
            $last_name = (isset($data['au']['lastName']) && $data['au']['lastName'])? $data['au']['lastName']:'';
        }

        if($first_name == '' OR $last_name == ''){
            $this->ci->session->set_flashdata('error', 'You must complete your profile with your first and last name!');
            redirect('account');
        }


        $total      = (isset($data['order']['total_base_price']) && $data['order']['total_base_price'])? (float)$data['order']['total_base_price']:0;
        $tva        = (isset($data['order']['total_vat']) && $data['order']['total_vat'])? (float)$data['order']['total_vat']:0;
        $total_tva  = $total+$tva;

        $f_request = array();

        $f_request['f_order_number'] = (isset($data['order']['order_code']) && $data['order']['order_code'])? $data['order']['order_code']:'';//'order number';
        $f_request['f_amount'] = (float)$total_tva;//(float)21.59;
        $f_request['f_currency'] = (isset($data['order']['cur']) && $data['order']['cur'])? $data['order']['cur']:'';//'RON/EUR/USD'; // choose one currency
        //$f_request['f_auth_minutes'] = 20; // 0 - waiting forever, 20 - default (in minutes)
        $f_request['f_language'] = 'IT'; // RO / EN / HU / IT / FR / DE / ES

        $customer_info = array();
        //pre($data);
        //contact
        $customer_info['contact']['f_email'] = (isset($data['order']['Billing_email']) && $data['order']['Billing_email'])? $data['order']['Billing_email']:'';//'email@domain.com';    // must not be empty. If empty don't send this tag, it will be filled in PO interface
        $customer_info['contact']['f_phone'] = (isset($data['order']['bill_phone']) && $data['order']['bill_phone'])? $data['order']['bill_phone']:'';//'0231100100';        // must not be empty, minimum 4 characters. If empty don't send this tag, it will be filled in PO interface
        $customer_info['contact']['f_mobile_number'] = (isset($data['order']['bill_phone']) && $data['order']['bill_phone'])? $data['order']['bill_phone']:'';//'0799999999';
        $customer_info['contact']['f_send_sms'] = 1;                   // 1 - sms client notification 0 - no notification
        $customer_info['contact']['f_first_name'] = $first_name;//'first name';        // must not be empty. If empty don't send this tag, it will be filled in PO interface
        $customer_info['contact']['f_last_name'] = $last_name;//'last name';            // must not be empty. If empty don't send this tag, it will be filled in PO interface
        //$customer_info['contact']['f_middle_name'] 	 = '';

        //invoice
        if($data['order']['bill_client_type'] == 2){
            $customer_info['invoice']['f_company'] = (isset($data['order']['bill_company_legal_name']) && $data['order']['bill_company_legal_name'])? $data['order']['bill_company_legal_name']:'';//'Test company';        // optional
            $customer_info['invoice']['f_cui'] = (isset($data['order']['bill_company_vat_num']) && $data['order']['bill_company_vat_num'])? $data['order']['bill_company_vat_num']:'';//'111111';            // optional
            $customer_info['invoice']['f_reg_com'] = '';//'J55/99/2000';        // optional
        }else{
            $customer_info['invoice']['f_cnp'] = (isset($data['order']['bill_person_tax_code']) && $data['order']['bill_person_tax_code'])? $data['order']['bill_person_tax_code']:'';//'9999999999999';        // optional
        }

        $customer_info['invoice']['f_zip'] = (isset($data['order']['Billing_address_pc']) && $data['order']['Billing_address_pc'])? $data['order']['Billing_address_pc']:'';//'999999';            // optional
        $customer_info['invoice']['f_country'] = (isset($data['order']['Billing_address_country']) && $data['order']['Billing_address_country'])? $data['order']['Billing_address_country']:'IT';//'Romania';            // must not be empty. If empty don't send this tag, it will be filled in PO interface
        $customer_info['invoice']['f_state'] = (isset($data['order']['Billing_address_province']) && $data['order']['Billing_address_province'])? $data['order']['Billing_address_province']:'';//'Bucuresti';            // must not be empty. If empty don't send this tag, it will be filled in PO interface
        $customer_info['invoice']['f_city'] = (isset($data['order']['Billing_address_city']) && $data['order']['Billing_address_city'])? $data['order']['Billing_address_city']:'';//'Bucuresti';            // must not be empty. If empty don't send this tag, it will be filled in PO interface
        $customer_info['invoice']['f_address'] = (isset($data['order']['Billing_address']) && $data['order']['Billing_address'])? $data['order']['Billing_address']:'';//'Address';            // must not be empty. If empty don't send this tag, it will be filled in PO interface

        $f_request['customer_info'] = $customer_info;

        $shipping_info = array();

        $shipping_info['same_info_as'] = 0; // 0 - different info, 1- same info as customer_info

        //contact
        $shipping_info['contact']['f_email'] = (isset($data['order']['Billing_email']) && $data['order']['Billing_email'])? $data['order']['Billing_email']:'';//'email@domain.com';
        $shipping_info['contact']['f_phone'] = (isset($data['order']['bill_phone']) && $data['order']['bill_phone'])? $data['order']['bill_phone']:'';//'0231999999';
        $shipping_info['contact']['f_mobile_number'] = (isset($data['order']['bill_phone']) && $data['order']['bill_phone'])? $data['order']['bill_phone']:'';//'0749999999';
        $shipping_info['contact']['f_send_sms'] = 0;                   // 1 - sms client notification 0 - no notification
        $shipping_info['contact']['f_first_name'] = $first_name;//'first name';
        $shipping_info['contact']['f_last_name'] = $last_name;//'last name';
        //$shipping_info['contact']['f_middle_name'] 	 = '';

        //address
        if($data['order']['bill_client_type'] == 2){
            $shipping_info['address']['f_company'] =  (isset($data['order']['bill_company_legal_name']) && $data['order']['bill_company_legal_name'])? $data['order']['bill_company_legal_name']:'';//'test company';
        }
        $shipping_info['address']['f_zip'] = (isset($data['order']['Billing_address_pc']) && $data['order']['Billing_address_pc'])? $data['order']['Billing_address_pc']:'';//'999999';
        $shipping_info['address']['f_country'] = (isset($data['order']['Billing_address_country']) && $data['order']['Billing_address_country'])? $data['order']['Billing_address_country']:'IT';
        $shipping_info['address']['f_state'] = (isset($data['order']['Billing_address_province']) && $data['order']['Billing_address_province'])? $data['order']['Billing_address_province']:'';//'Bucuresti';
        $shipping_info['address']['f_city'] = (isset($data['order']['Billing_address_city']) && $data['order']['Billing_address_city'])? $data['order']['Billing_address_city']:'';//'Bucuresti';
        $shipping_info['address']['f_address'] = (isset($data['order']['Billing_address']) && $data['order']['Billing_address'])? $data['order']['Billing_address']:'';//substr('Address', 0, 100);

        // shipping info may not be sent if no shipping is necessary (virtual products)
        $f_request['shipping_info'] = $shipping_info;

        //var_dump($f_request);
        //die();

        $transaction_relay_response = array();

        $transaction_relay_response['f_relay_response_url'] = base_url()."order/response/".$f_request['f_order_number'];//'http://domain.com/auth_response.php';

        //echo $transaction_relay_response['f_relay_response_url'];die();

        // INFO f_relay_method
        $transaction_relay_response['f_relay_method'] = 'POST_S2S_PO_PAGE'; // PTOR, POST_S2S_PO_PAGE, POST_S2S_MT_PAGE, SOAP_PO_PAGE, SOAP_MT_PAGE
        // * if your website has SSL enabled, use PTOR relay method. It will redirect the client to merchant website at f_relay_response_url
        // * if your website DOES NOT USE SSL, use POST_S2S_PO_PAGE. It will show the PlatiOnline response page and we will send the tranzaction response SERVER-to-SERVER to f_relay_response_url so you can update the order status
        // END INFO f_relay_method

        $transaction_relay_response['f_post_declined'] = 1; // Valoarea = 1	(default value; sistemul PO trimite rezultatul la f_relay_response_url prin metoda f_relay_method)	Valoarea = 0	(systemul PO trimite rezultatul doar pentru tranzactiile "Autorizate" si "In curs de verificare" la <f_relay_response_url> prin metoda <f_relay_method>)
        $transaction_relay_response['f_relay_handshake'] = 1; // default 1
        $f_request['transaction_relay_response'] = $transaction_relay_response;

        //$f_request['tracking_script'] = 'tracking script';

        $f_request['f_order_cart'] = array();

        // PLEASE READ
        // $item['itemprice'] - the price WITOUT VAT for 1 piece of the product
        // $item['vat']		  - VAT for 1 piece of the product * $item['qty']
        // END PLEASE READ

        for ($i = 0; $i < 1; $i++) {
            $item = array();

            $item['prodid'] = 1;
            $item['name'] = substr('Servicii de curierat' . $i, 0, 250);
            $item['description'] = substr('Plata pentru servicii de curierat' . $i, 0, 250);
            $item['qty'] = 1;
            $item['itemprice'] = (float)$total; // price WITOUT VAT for 1 piece of the product
            $item['vat'] = (float)$tva;  // VAT for 1 piece of the product * $item['qty']
            $item['stamp'] = date('Y-m-d');
            $item['prodtype_id'] = 0;

            $f_request['f_order_cart'][] = $item;
        }

        // ACTIVATE ONLY IF YOU USE COUPONS
        /*
        //coupon 1
        $coupon1 = array();
        $coupon1['key'] 		= '0002C';
        $coupon1['value'] 		= (float)10.00;
        $coupon1['percent'] 	= 1;
        $coupon1['workingname']	= 'Cupon reducere';
        $coupon1['type'] 		= 0;
        $coupon1['scop'] 		= 0;
        $coupon1['vat'] 		= (float)1.11;

        //coupon 2
        $coupon2 = array();
        $coupon2['key'] 		= '0002D';
        $coupon2['value'] 		= (float)7.50;
        $coupon2['percent'] 	= 0;
        $coupon2['workingname']	= 'Cupon reducere';
        $coupon2['type'] 		= 0;
        $coupon2['scop'] 		= 0;
        $coupon2['vat'] 		= (float)0.11;

        // declare $f_request['f_order_cart']['coupon1'], $f_request['f_order_cart']['coupon2']; we index the field ['coupon'] to have different names in array and to avoid overwriting the values
        // the array to xml method takes care of this case by looking for "coupon" substring
        $f_request['f_order_cart']['coupon1'] = $coupon1;
        $f_request['f_order_cart']['coupon2'] = $coupon2;
        */
        // END ACTIVATE ONLY IF YOU USE COUPONS

        //shipping
        $shipping = array();
        // $shipping['name'] = substr('Shipping 1', 0, 250);
        // $shipping['price'] = (float)15.5;
        // $shipping['pimg'] = 0;
        // $shipping['vat'] = (float)2.5;

        $f_request['f_order_cart']['shipping'] = $shipping;

        $f_request['f_order_string'] = 'Order number ' . $f_request['f_order_number'] . ' on website '.base_url();

        //custom merchant fields - they will be returned to you in f_relay_response_url by POST or GET or SOAP, according to where you send them
        //$f_request['merchants_fields']['PostQueryString'] = 'postmerchant=posttestmerch'; //PostQueryString
        //$f_request['merchants_fields']['GetQueryString'] 	= 'getmerchant=gettestmerch'; //GetQueryString
        //$f_request['merchants_fields']['SoapTags'] 		= '<field1>value1</field1><field2>value2</field2>'; //SoapTags

        //up in constructor
        //require_once(APPPATH."libraries/po/PlatiOnline/PO5.php");
        //set before class
        //use PlatiOnline\PO5 as PO5;

        $po = new PO5();

        //var_dump($po);die();

        //f_login and RSA key will be saved in config
        $po->f_login = $this->ci->config->item('po_f_login');//'F_LOGIN from merchant interface';

        // INFO f_website
        // * if you ARE USING the same PlatiOnline account for multiple websites
        // - go to https://merchants.plationline.ro, in Settings tab, POS/Website button, click Add a new POS/website and add your websites
        // - after we approve your websites, please use Website/POS value for $f_request['f_website']

        $f_request['f_website'] = str_replace('www.', '', $_SERVER['SERVER_NAME']);
        // END INFO f_website

        // RSA Public AUTH [Merchant side]:
        $po->setRSAKeyEncrypt($this->ci->config->item('po_public_key'));//'RSA Public AUTH [Merchant side]'
        // IV AUTH:
        $po->setIV($this->ci->config->item('po_iv'));
        //end f_login and RSA key will be saved in config

        // test mode: 0 - disabled, 1 - enabled
        $po->test_mode = 0;

        // plationline authorization call
        // simple payment, no installments / FARA RATE
        $auth_response = $po->auth($f_request, 2); // parameter 1 - request content, 2 - f_action (2 simple payment, 12 - ghiseu Posta romana, 13 - ghiseu Raiffeisen Bank)
        //var_dump($auth_response);die();

        $redirect_url = $po->get_xml_tag_content($auth_response, 'PO_REDIRECT_URL');
        $transid = $po->get_xml_tag_content($auth_response, 'X_TRANS_ID');
        if (!empty($redirect_url)) {
            header('Location: ' . $redirect_url);
        } else {
            throw new \Exception('ERROR: Serverul nu a intors URL-ul pentru a finaliza tranzactia!');
        }

        // FOR INSTALLMENTS / PENTRU RATE

        // $f_request['f_rate'] = (int)'number of installments chosen by the customer';
        // EX: $f_request['f_rate'] = 6;

        // AUTH CALL FOR INSTALLMENTS
        // $po->auth($f_request, 16); 10 - Raiffeisen Bank installments, 16 - Banca Transilvania installments, 18 - Alpha Bank Installments, 22 - BRD

        // END FOR INSTALLMENTS / PENTRU RATE

        // FOR RECCURENCE

        // $f_request['f_recurring_frequency'] 		   = 3;  // frequency: 1 - weekly, 2 - every 2 weeks, 3 - monthly, 4 - quarterly, 5 - semestrial
        // $f_request['f_recurring_expiration_date']   = ''; // reccurence expiry date (format YYYY-mm-dd) - maximum 24 months
        // $po->auth($f_request, 20);

        // END FOR RECCURENCE

    }

    public function response($data){

        $this->ci->load->model('orders_manager_m');

        $po = new PO5();
        // RSA Private ITSN [Merchant side]:
        $po->setRSAKeyDecrypt($this->ci->config->item('po_private_key'));//'RSA Private ITSN [Merchant side]'
        //IV ITSN:
        $po->setIVITSN($this->ci->config->item('po_iv_itsn'));//'IV ITSN'

        // POST response for PTOR, POST_S2S_PO_PAGE, POST_S2S_MT_PAGE of f_relay_method
        // PTOR is recommended, a redirect from PO server to response page from merchant website is performed
        // POST_S2S_PO_PAGE - POST response Server2Server, PlatiOnline template
        // POST_S2S_MT_PAGE - POST response Server2Server, merchant template
        // SOAP_PO_PAGE - SOAP response, PlatiOnline template
        // SOAP_MT_PAGE - SOAP response, merchant template

        $authorization_response = $po->auth_response($data['po']['F_Relay_Message'], $data['po']['F_Crypt_Message']);

        //the other POST fields are the fields sent by the merchant in $f_request['merchants_fields'] field, plain text

        /**************************************************************************************************
         **************************************************************************************************
         ***                                                                                            ***
         ***        $authorization_response looks like this:                                            ***
         ***    array(1) {                                                                              ***
         ***             ["PO_AUTH_RESPONSE"]=>                                                         ***
         ***             array(14) {                                                                    ***
         ***                ["F_LOGIN"] => string(15) "PO WWW.DEMO.RO"                                  ***
         ***                ["F_WEBSITE"] => string(0) "WWW.DEMO.RO"                                    ***
         ***                ["F_TEST_REQUEST"] => string(1) "1"                                         ***
         ***                ["F_TIMESTAMP"] => string(38) "Fri , 14 Mar 2014 15:10:56 +0300 (GMT)"      ***
         ***                ["F_ORDER_NUMBER"] => string(12) "Order 1 test"                             ***
         ***                ["F_ACTION"] => string(1) "2"                                               ***
         ***                ["F_AMOUNT"] => string(5) "11.99"                                           ***
         ***                ["F_CURRENCY"] => string(3) "RON"                                           ***
         ***                ["X_RESPONSE_CODE"] => string(1) "2"                                        ***
         ***                ["X_RESPONSE_REASON_CODE"] => string(5) "60036"                             ***
         ***                ["X_RESPONSE_REASON_TEXT"] => string(11) "Autorizată"                       ***
         ***                ["X_AUTH_CODE"] => string(6) "POTEST"                                       ***
         ***                ["X_ACTION_CODE"] => string(2) "NA"                                         ***
         ***                ["X_TRANS_ID"] => string(7) "1175053"                                       ***
         ***            }                                                                               ***
         ***        }                                                                                   ***
         ***                                                                                            ***
         **************************************************************************************************
         **************************************************************************************************/

        $X_RESPONSE_CODE = $po->get_xml_tag_content($authorization_response, 'X_RESPONSE_CODE');

        // ---------------------------------------------------------------------------------------------------------------------------//

        /////////////////////////////////////////
        // 									   //
        //         raspuns metoda PTOR         //
        // 									   //
        /////////////////////////////////////////


        switch ($X_RESPONSE_CODE) {
            case '2':
                //	authorized
                $errorMessage = 'The transaction was authorized!';


                // please update the order status in your system
                break;
            case '13':
                //	on hold
                $errorMessage = 'The transaction is on hold, additional checking is needed!';

                // please update the order status in your system
                break;
            case '8':
                //	declined
                $errorMessage = 'The transaction was declined! Reason: ' . $po->get_xml_tag_content($authorization_response, 'X_RESPONSE_REASON_TEXT') . '.';

                // please update the order status in your system
                break;
            case '10';
                //	error
                $errorMessage = 'An error was encountered in authorization process';

                //8 = 5 code Canceled  Error

                // please update the order status in your system
                break;
        }
    }

    function refund($data)
    {

        //refund call by PlatiOnline
        $po = new PO5();

        // RSA Public AUTH [Merchant side]:
        $po->setRSAKeyEncrypt($this->ci->config->item('po_public_key'));
        // IV AUTH:
        $po->setIV($this->ci->config->item('po_iv'));

        $po->f_login = $this->ci->config->item('po_f_login');

        $f_request['f_website'] = $po->f_login;
        $f_request['f_order_number'] = $data['order']['order_code'];//order_code trimis la plata
        $f_request['x_trans_id'] = $data['order']['transaction_id'];//transaction_id preluat dupa plata in itsn

        $response_refund = $po->refund($f_request, 1);

        if ($po->get_xml_tag_content($response_refund, 'PO_ERROR_CODE') == 1) {
            throw new Exception('<b>ERROR</b>: ' . $po->get_xml_tag_content($response_refund, 'PO_ERROR_REASON'));

            $errorMessage = 'Error refund.';


        } else {
            switch ($po->get_xml_tag_content($response_refund, 'X_RESPONSE_CODE')) {
                case '1':
                    $errorMessage = 'The amount of ' . $po->get_xml_tag_content($response_refund, 'F_AMOUNT') . ' successfully refunded';



                    break;
                case '10':
                    $errorMessage =  'Errors occured, transaction NOT REFUNDED';


                    break;
            }
        }
    }

    function itsn($data)
    {
        $this->ci->load->model('orders_manager_m');
        $this->ci->load->model('awb_model');

        //decript ITSN call sent by PlatiOnline
        $po = new PO5();
        // RSA Private ITSN [Merchant side]:
        $po->setRSAKeyDecrypt($this->ci->config->item('po_private_key'));
        //IV ITSN:
        $po->setIVITSN($this->ci->config->item('po_iv_itsn'));

        $call_itsn = $po->itsn($data['po']['f_itsn_message'], $data['po']['f_crypt_message']);

        //set query config
        // RSA Public AUTH [Merchant side]:
        $po->setRSAKeyEncrypt($this->ci->config->item('po_public_key'));
        // IV AUTH:
        $po->setIV($this->ci->config->item('po_iv'));

        $po->f_login = $this->ci->config->item('po_f_login');

        $f_request['f_website'] = $po->f_login;
        $f_request['f_order_number'] = $po->get_xml_tag_content($call_itsn, 'F_ORDER_NUMBER');
        $f_request['x_trans_id'] = $po->get_xml_tag_content($call_itsn, 'X_TRANS_ID');
        $raspuns_itsn = $po->query($f_request, 0);

        // in case of error:

        //  <po_query_response>
        //		<po_error_code>1</po_error_code>
        //		<po_error_reason><![CDATA[Invalid request]]></po_error_reason>
        //	</po_query_response>

        if ($po->get_xml_tag_content($raspuns_itsn, 'PO_ERROR_CODE') == 1) {
            throw new Exception($po->get_xml_tag_content($raspuns_itsn, 'PO_ERROR_REASON'));
        } else {
            $order = $po->get_xml_tag($raspuns_itsn, 'ORDER');
            $tranzaction = $po->get_xml_tag($order, 'TRANZACTION');

            $F_ORDER_NUMBER = $po->get_xml_tag_content($order, 'F_ORDER_NUMBER');
            $X_TRANS_ID = $po->get_xml_tag_content($tranzaction, 'X_TRANS_ID');
            $starefin1 = $po->get_xml_tag_content($po->get_xml_tag($tranzaction, 'STATUS_FIN1'), 'CODE');
            $starefin2 = $po->get_xml_tag_content($po->get_xml_tag($tranzaction, 'STATUS_FIN2'), 'CODE');

            if(startsWith($F_ORDER_NUMBER,'cre_')){
                $sys_id = str_replace('cre_','',$F_ORDER_NUMBER);
                $infoOrder =  $this->ci->orders_manager_m->get($sys_id);
                if($infoOrder['order_meta'] == ''){
                    $meta = null;
                }else{
                    $meta = json_decode($infoOrder['order_meta'],true);
                }
                $data['order'] = $infoOrder;
                if(isset($infoOrder) && $infoOrder)
                {

                    $data['order']['order_id']  = $infoOrder['order_id'];
                    $data['order']['id_order']  = $infoOrder['order_id'];

                    //add transaction_id in orders
                    $this->ci->db->where('order_id',$data['order']['order_id'])->update('order_payments',[
                                                                'transaction_id'=> $X_TRANS_ID
                                                            ]);

                    $stare1 = '<f_response_code>1</f_response_code>';

                    switch ($starefin1) {
                        case '13':
                            //$starefin = 'on-hold';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is on hold, ITSN';

                            break;
                        case '2':
                            //$starefin = 'authorized';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is authorized, ITSN';
                            //2 = 2 code authorized


                            $user = $this->ci->users_m->get($data['order']['id_user']);



                            break;
                        case '8':
                            //$starefin = 'declined';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is declined, ITSN';

                            break;
                        case '3':
                            //$starefin = 'pending settle';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is pending settle, ITSN';


                            break;
                        case '5':
                            /* Verify starefin2 status*/
                            switch ($starefin2) {
                                case '1':
                                    //$starefin='pending refund';
                                    // please update the order status in your system
                                    $errorMessage = 'The transaction is pending refund, ITSN';

                                    break;
                                case '2':
                                    //$starefin='refund';
                                    // please update the order status in your system
                                    $errorMessage = 'The transaction is refund, ITSN';

                                    //1 = 6 code Refunded

                                    break;
                                case '3':
                                    //$starefin='payment refused';
                                    // please update the order status in your system
                                    $errorMessage = 'The transaction is payment refused, ITSN';

                                    //1 = 5 code payment cancelled

                                    break;
                                case '4':
                                    //$starefin='settled';
                                    // please update the order status in your system
                                    $errorMessage = 'The transaction is settled, ITSN';
                                    ager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                                    //1 = 7 code settled

                                    break;
                            }
                            break;
                        case '6':
                            //$starefin= 'pending void';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is pending void, ITSN';

                            //6 = 1 code Pending payment

                            break;
                        case '7':
                            //$starefin='voided';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is voided, ITSN';

                            //7 = 5 code Payment cancelled

                            break;
                        case '9':
                            //$starefin='expired';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is expired, ITSN';

                            //9 = 5 code Payment cancelled

                            break;
                        case '10':
                        case '16':
                        case '17':
                            //$starefin='error';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is error, ITSN';

                            //10 16 17 = 5 code Payment cancelled

                            break;
                        case '1':
                            //$starefin='pending authorization';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is pending authorization, ITSN';

                            //1 = 4 code Paid preauthorized

                            break;
                        default:
                            $stare1 = '<f_response_code>0</f_response_code>';
                    }

                    /* send ITSN response */
                    $raspuns_xml = '<?xml version="1.0" encoding="UTF-8" ?>';
                    $raspuns_xml .= '<itsn>';
                    $raspuns_xml .= '<x_trans_id>' . $X_TRANS_ID . '</x_trans_id>';
                    $raspuns_xml .= '<merchServerStamp>' . date("Y-m-d H:m:s") . '</merchServerStamp>';
                    $raspuns_xml .= $stare1;
                    $raspuns_xml .= '</itsn>';

                    echo $raspuns_xml;
                }
            }else{
               $infoOrder =  $this->ci->awb_model->get_order($F_ORDER_NUMBER);

                if(isset($infoOrder) && $infoOrder)
                {

                    $data['order']['id_order']  = $infoOrder['id_order'];

                    //add transaction_id in orders
                    $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'transaction_id'=> $X_TRANS_ID
                                                            ]);

                    $stare1 = '<f_response_code>1</f_response_code>';

                    switch ($starefin1) {
                        case '13':
                            //$starefin = 'on-hold';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is on hold, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'on_hold',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //13 = 1 code Pending payment
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>1,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);
                            break;
                        case '2':
                            //$starefin = 'authorized';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is authorized, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'authorized',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //2 = 2 code authorized
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>2,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);
                            break;
                        case '8':
                            //$starefin = 'declined';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is declined, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'declined',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //8 = 5 code Payment cancelled
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>5,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);
                            break;
                        case '3':
                            //$starefin = 'pending settle';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is pending settle, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'pending settle',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //3 = 1 code Pending Payment
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>1,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);

                            break;
                        case '5':
                            /* Verify starefin2 status*/
                            switch ($starefin2) {
                                case '1':
                                    //$starefin='pending refund';
                                    // please update the order status in your system
                                    $errorMessage = 'The transaction is pending refund, ITSN';
                                    $r = [
                                            'error_message'=>$errorMessage,
                                            'cod_eroare'=>$starefin2,
                                            'po_status' => 'pending refund',
                                            'order_refference' => $data['order']['id_order']
                                             ];

                                    $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                                    //1 = 6 code Refunded
                                    $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                        'pay_status'=>6,
                                                                        'payment_date'=>date('Y-m-d H:i:s')
                                                                    ]);
                                    break;
                                case '2':
                                    //$starefin='refund';
                                    // please update the order status in your system
                                    $errorMessage = 'The transaction is refund, ITSN';
                                    $r = [
                                            'error_message'=>$errorMessage,
                                            'cod_eroare'=>$starefin2,
                                            'po_status' => 'refund',
                                            'order_refference' => $data['order']['id_order']
                                             ];

                                    $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                                    //1 = 6 code Refunded
                                    $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                        'pay_status'=>7,
                                                                        'payment_date'=>date('Y-m-d H:i:s')
                                                                    ]);
                                    break;
                                case '3':
                                    //$starefin='payment refused';
                                    // please update the order status in your system
                                    $errorMessage = 'The transaction is payment refused, ITSN';
                                    $r = [
                                            'error_message'=>$errorMessage,
                                            'cod_eroare'=>$starefin2,
                                            'po_status' => 'payment refused',
                                            'order_refference' => $data['order']['id_order']
                                             ];

                                    $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                                    //1 = 5 code payment cancelled
                                    $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                        'pay_status'=>5,
                                                                        'payment_date'=>date('Y-m-d H:i:s')
                                                                    ]);
                                    break;
                                case '4':
                                    //$starefin='settled';
                                    // please update the order status in your system
                                    $errorMessage = 'The transaction is settled, ITSN';
                                    $r = [
                                            'error_message'=>$errorMessage,
                                            'cod_eroare'=>$starefin2,
                                            'po_status' => 'settled',
                                            'order_refference' => $data['order']['id_order']
                                             ];

                                    $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                                    //1 = 7 code settled
                                    $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                        'pay_status'=>2,
                                                                        'payment_date'=>date('Y-m-d H:i:s')
                                                                    ]);
                                    break;
                            }
                            break;
                        case '6':
                            //$starefin= 'pending void';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is pending void, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'pending void',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //6 = 1 code Pending payment
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>9,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);
                            break;
                        case '7':
                            //$starefin='voided';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is voided, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'voided',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //7 = 5 code Payment cancelled
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>10,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);
                            break;
                        case '9':
                            //$starefin='expired';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is expired, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'expired',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //9 = 5 code Payment cancelled
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>11,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);
                            break;
                        case '10':
                        case '16':
                        case '17':
                            //$starefin='error';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is error, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'error',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //10 16 17 = 5 code Payment cancelled
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>12,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);
                            break;
                        case '1':
                            //$starefin='pending authorization';
                            // please update the order status in your system
                            $errorMessage = 'The transaction is pending authorization, ITSN';
                            $r = [
                                    'error_message'=>$errorMessage,
                                    'cod_eroare'=>$starefin1,
                                    'po_status' => 'pending authorization',
                                    'order_refference' => $data['order']['id_order']
                                     ];

                            $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'PlatiOnline',$r);

                            //1 = 4 code Paid preauthorized
                            $this->ci->db->where('id_order',$data['order']['id_order'])->update('orders',[
                                                                'pay_status'=>13,
                                                                'payment_date'=>date('Y-m-d H:i:s')
                                                            ]);
                            break;
                        default:
                            $stare1 = '<f_response_code>0</f_response_code>';
                    }

                    /* send ITSN response */
                    $raspuns_xml = '<?xml version="1.0" encoding="UTF-8" ?>';
                    $raspuns_xml .= '<itsn>';
                    $raspuns_xml .= '<x_trans_id>' . $X_TRANS_ID . '</x_trans_id>';
                    $raspuns_xml .= '<merchServerStamp>' . date("Y-m-d H:m:s") . '</merchServerStamp>';
                    $raspuns_xml .= $stare1;
                    $raspuns_xml .= '</itsn>';

                    echo $raspuns_xml;
                }
            }



        }
    }



    function credits($data)
    {

        $first_name = (isset($data['bill_first_name']) && $data['bill_first_name'])? $data['bill_first_name']:'';
        $last_name = (isset($data['bill_last_name']) && $data['bill_last_name'])? $data['bill_last_name']:'';


        if($first_name == '' OR $last_name == ''){
            $this->ci->session->set_flashdata('error', 'You must complete your profile with your first and last name!');
            redirect('account');
        }




        $f_request = array();

        $f_request['f_order_number'] = 'cre_'.$data['order_number'];
        $f_request['f_amount'] = (float)$data['amount'];
        $f_request['f_currency'] = 'EUR';
        //$f_request['f_auth_minutes'] = 20; // 0 - waiting forever, 20 - default (in minutes)
        $f_request['f_language'] = 'IT'; // RO / EN / HU / IT / FR / DE / ES

        $customer_info = array();
        //pre($data);
        //contact
        $customer_info['contact']['f_email'] = $data['email'];
        $customer_info['contact']['f_phone'] = $data['phone'];
        $customer_info['contact']['f_mobile_number'] = $data['phone'];
        $customer_info['contact']['f_send_sms'] = 0;
        $customer_info['contact']['f_first_name'] = $first_name;
        $customer_info['contact']['f_last_name'] = $last_name;
        //$customer_info['contact']['f_middle_name'] 	 = '';

        //invoice
        if($data['client_type'] == 2){
            $customer_info['invoice']['f_company'] = $data['company_legal_name'];
            $customer_info['invoice']['f_cui'] = $data['company_vat_num'];
            $customer_info['invoice']['f_reg_com'] = '';//'J55/99/2000';        // optional

            $customer_info['invoice']['f_zip'] = $data['company_address_pc'];
            $customer_info['invoice']['f_country'] = 'Italia';//$data['company_address_country'];
            $customer_info['invoice']['f_state'] = $data['company_address_province'];
            $customer_info['invoice']['f_city'] = $data['company_address_city'];
            $customer_info['invoice']['f_address'] = $data['company_address'];

        }else{
            $customer_info['invoice']['f_cnp'] = $data['person_codice_fiscale'];

            $customer_info['invoice']['f_zip'] = $data['person_address_pc'];
            $customer_info['invoice']['f_country'] = 'Italia';//$data['person_address_country'];
            $customer_info['invoice']['f_state'] = $data['person_address_province'];
            $customer_info['invoice']['f_city'] = $data['person_address_city'];
            $customer_info['invoice']['f_address'] = $data['person_address_pc'];
        }


        $f_request['customer_info'] = $customer_info;

        $shipping_info = array();

        $shipping_info['same_info_as'] = 0; // 0 - different info, 1- same info as customer_info

        //contact
        $shipping_info['contact']['f_email'] = $data['email'];
        $shipping_info['contact']['f_phone'] = $data['phone'];
        $shipping_info['contact']['f_mobile_number'] = $data['phone'];
        $shipping_info['contact']['f_send_sms'] = 0;                   // 1 - sms client notification 0 - no notification
        $shipping_info['contact']['f_first_name'] = $first_name;//'first name';
        $shipping_info['contact']['f_last_name'] = $last_name;//'last name';
        //$shipping_info['contact']['f_middle_name'] 	 = '';


        if($data['client_type'] == 2){
            $shipping_info['invoice']['f_company'] = $data['company_legal_name'];

            $shipping_info['address']['f_zip'] = $data['company_address_pc'];
            $shipping_info['address']['f_country'] = 'Italia';//$data['company_address_country'];
            $shipping_info['address']['f_state'] = $data['company_address_province'];
            $shipping_info['address']['f_city'] = $data['company_address_city'];
            $shipping_info['address']['f_address'] = $data['company_address'];

        }else{

            $shipping_info['address']['f_zip'] = $data['person_address_pc'];
            $shipping_info['address']['f_country'] = 'Italia';//$data['person_address_country'];
            $shipping_info['address']['f_state'] = $data['person_address_province'];
            $shipping_info['address']['f_city'] = $data['person_address_city'];
            $shipping_info['address']['f_address'] = $data['person_address_pc'];
        }


        // shipping info may not be sent if no shipping is necessary (virtual products)
        $f_request['shipping_info'] = $shipping_info;

        //var_dump($f_request);
        //die();

        $transaction_relay_response = array();

        $transaction_relay_response['f_relay_response_url'] = base_url('accounts/credits/'.$f_request['f_order_number']);

        //echo $transaction_relay_response['f_relay_response_url'];die();

        // INFO f_relay_method
        $transaction_relay_response['f_relay_method'] = 'POST_S2S_PO_PAGE'; // PTOR, POST_S2S_PO_PAGE, POST_S2S_MT_PAGE, SOAP_PO_PAGE, SOAP_MT_PAGE
        // * if your website has SSL enabled, use PTOR relay method. It will redirect the client to merchant website at f_relay_response_url
        // * if your website DOES NOT USE SSL, use POST_S2S_PO_PAGE. It will show the PlatiOnline response page and we will send the tranzaction response SERVER-to-SERVER to f_relay_response_url so you can update the order status
        // END INFO f_relay_method

        $transaction_relay_response['f_post_declined'] = 1; // Valoarea = 1	(default value; sistemul PO trimite rezultatul la f_relay_response_url prin metoda f_relay_method)	Valoarea = 0	(systemul PO trimite rezultatul doar pentru tranzactiile "Autorizate" si "In curs de verificare" la <f_relay_response_url> prin metoda <f_relay_method>)
        $transaction_relay_response['f_relay_handshake'] = 1; // default 1
        $f_request['transaction_relay_response'] = $transaction_relay_response;

        //$f_request['tracking_script'] = 'tracking script';

        $f_request['f_order_cart'] = array();

        // PLEASE READ
        // $item['itemprice'] - the price WITOUT VAT for 1 piece of the product
        // $item['vat']		  - VAT for 1 piece of the product * $item['qty']
        // END PLEASE READ


            $item = [];

            $item['prodid'] = 2;
            $item['name'] = substr(__t('credits_product_name_on_invoice'), 0, 250);
            $item['description'] = substr(__t('credits_product_name_on_invoice'), 0, 250);
            $item['qty'] = 1;
            $item['itemprice'] = (float)round($data['order']['total_value_vat_exc'],2); // price WITOUT VAT for 1 piece of the product
            $item['vat'] = (float)round($data['order']['vat_value'],2);  // VAT for 1 piece of the product * $item['qty']
            $item['stamp'] = date('Y-m-d');
            $item['prodtype_id'] = 0;

            $f_request['f_order_cart'][] = $item;


        //shipping
        $shipping = array();
        // $shipping['name'] = substr('Shipping 1', 0, 250);
        // $shipping['price'] = (float)15.5;
        // $shipping['pimg'] = 0;
        // $shipping['vat'] = (float)2.5;

        $f_request['f_order_cart']['shipping'] = $shipping;

        $f_request['f_order_string'] = 'Order number ' . $f_request['f_order_number'] . ' on website '.base_url();

        //custom merchant fields - they will be returned to you in f_relay_response_url by POST or GET or SOAP, according to where you send them
        //$f_request['merchants_fields']['PostQueryString'] = 'postmerchant=posttestmerch'; //PostQueryString
        //$f_request['merchants_fields']['GetQueryString'] 	= 'getmerchant=gettestmerch'; //GetQueryString
        //$f_request['merchants_fields']['SoapTags'] 		= '<field1>value1</field1><field2>value2</field2>'; //SoapTags

        //up in constructor
        //require_once(APPPATH."libraries/po/PlatiOnline/PO5.php");
        //set before class
        //use PlatiOnline\PO5 as PO5;

        $po = new PO5();

        //var_dump($po);die();

        //f_login and RSA key will be saved in config
        $po->f_login = $this->ci->config->item('po_f_login');//'F_LOGIN from merchant interface';

        // INFO f_website
        // * if you ARE USING the same PlatiOnline account for multiple websites
        // - go to https://merchants.plationline.ro, in Settings tab, POS/Website button, click Add a new POS/website and add your websites
        // - after we approve your websites, please use Website/POS value for $f_request['f_website']

        $f_request['f_website'] = str_replace('www.', '', $_SERVER['SERVER_NAME']);
        // END INFO f_website

        // RSA Public AUTH [Merchant side]:
        $po->setRSAKeyEncrypt($this->ci->config->item('po_public_key'));//'RSA Public AUTH [Merchant side]'
        // IV AUTH:
        $po->setIV($this->ci->config->item('po_iv'));
        //end f_login and RSA key will be saved in config

        // test mode: 0 - disabled, 1 - enabled
        $po->test_mode = 0;

        // plationline authorization call
        // simple payment, no installments / FARA RATE
        $auth_response = $po->auth($f_request, 2); // parameter 1 - request content, 2 - f_action (2 simple payment, 12 - ghiseu Posta romana, 13 - ghiseu Raiffeisen Bank)
        //var_dump($auth_response);die();

        $redirect_url = $po->get_xml_tag_content($auth_response, 'PO_REDIRECT_URL');
        $transid = $po->get_xml_tag_content($auth_response, 'X_TRANS_ID');
        if (!empty($redirect_url)) {
            header('Location: ' . $redirect_url);
        } else {
            throw new \Exception('ERROR: Serverul nu a intors URL-ul pentru a finaliza tranzactia!');
        }

        // FOR INSTALLMENTS / PENTRU RATE

        // $f_request['f_rate'] = (int)'number of installments chosen by the customer';
        // EX: $f_request['f_rate'] = 6;

        // AUTH CALL FOR INSTALLMENTS
        // $po->auth($f_request, 16); 10 - Raiffeisen Bank installments, 16 - Banca Transilvania installments, 18 - Alpha Bank Installments, 22 - BRD

        // END FOR INSTALLMENTS / PENTRU RATE

        // FOR RECCURENCE

        // $f_request['f_recurring_frequency'] 		   = 3;  // frequency: 1 - weekly, 2 - every 2 weeks, 3 - monthly, 4 - quarterly, 5 - semestrial
        // $f_request['f_recurring_expiration_date']   = ''; // reccurence expiry date (format YYYY-mm-dd) - maximum 24 months
        // $po->auth($f_request, 20);

        // END FOR RECCURENCE

    }
    public function response_credits($data){

        $this->ci->load->model('orders_manager_m');

        $po = new PO5();
        // RSA Private ITSN [Merchant side]:
        $po->setRSAKeyDecrypt($this->ci->config->item('po_private_key'));//'RSA Private ITSN [Merchant side]'
        //IV ITSN:
        $po->setIVITSN($this->ci->config->item('po_iv_itsn'));//'IV ITSN'

        // POST response for PTOR, POST_S2S_PO_PAGE, POST_S2S_MT_PAGE of f_relay_method
        // PTOR is recommended, a redirect from PO server to response page from merchant website is performed
        // POST_S2S_PO_PAGE - POST response Server2Server, PlatiOnline template
        // POST_S2S_MT_PAGE - POST response Server2Server, merchant template
        // SOAP_PO_PAGE - SOAP response, PlatiOnline template
        // SOAP_MT_PAGE - SOAP response, merchant template

        $authorization_response = $po->auth_response($data['po']['F_Relay_Message'], $data['po']['F_Crypt_Message']);

        //the other POST fields are the fields sent by the merchant in $f_request['merchants_fields'] field, plain text

        /**************************************************************************************************
         **************************************************************************************************
         ***                                                                                            ***
         ***        $authorization_response looks like this:                                            ***
         ***    array(1) {                                                                              ***
         ***             ["PO_AUTH_RESPONSE"]=>                                                         ***
         ***             array(14) {                                                                    ***
         ***                ["F_LOGIN"] => string(15) "PO WWW.DEMO.RO"                                  ***
         ***                ["F_WEBSITE"] => string(0) "WWW.DEMO.RO"                                    ***
         ***                ["F_TEST_REQUEST"] => string(1) "1"                                         ***
         ***                ["F_TIMESTAMP"] => string(38) "Fri , 14 Mar 2014 15:10:56 +0300 (GMT)"      ***
         ***                ["F_ORDER_NUMBER"] => string(12) "Order 1 test"                             ***
         ***                ["F_ACTION"] => string(1) "2"                                               ***
         ***                ["F_AMOUNT"] => string(5) "11.99"                                           ***
         ***                ["F_CURRENCY"] => string(3) "RON"                                           ***
         ***                ["X_RESPONSE_CODE"] => string(1) "2"                                        ***
         ***                ["X_RESPONSE_REASON_CODE"] => string(5) "60036"                             ***
         ***                ["X_RESPONSE_REASON_TEXT"] => string(11) "Autorizată"                       ***
         ***                ["X_AUTH_CODE"] => string(6) "POTEST"                                       ***
         ***                ["X_ACTION_CODE"] => string(2) "NA"                                         ***
         ***                ["X_TRANS_ID"] => string(7) "1175053"                                       ***
         ***            }                                                                               ***
         ***        }                                                                                   ***
         ***                                                                                            ***
         **************************************************************************************************
         **************************************************************************************************/

        $X_RESPONSE_CODE = $po->get_xml_tag_content($authorization_response, 'X_RESPONSE_CODE');

        // ---------------------------------------------------------------------------------------------------------------------------//

        /////////////////////////////////////////
        // 									   //
        //         raspuns metoda PTOR         //
        // 									   //
        /////////////////////////////////////////

        $data['order']['id_order'] = $data['order']['order_id'];
        switch ($X_RESPONSE_CODE) {
            case '2':
                //	authorized
                $errorMessage = 'The transaction was authorized!';

                $r = [
                        'error_message'=>$errorMessage,
                        'cod_eroare'=>$X_RESPONSE_CODE,
                        'po_status' => 'authorized',
                        'order_refference' => $data['order']['id_order'],
                        'authorization_response' => $authorization_response
                         ];

                $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'Credits PlatiOnline',$r);

                $this->ci->db->where('order_id',$data['order']['id_order'])->update('order_payments',[
                    'order_status'=>2,
                    'payment_reg_date'=>date('Y-m-d H:i:s')
                ]);


                $this->ci->load->model('users_m');
                $user = $this->ci->users_m->get($data['order']['id_user']);

                $meta = $data['order']['order_meta'];
                if(isset($meta['credits'])){
                    if(!isset($meta['credit_rewarded'])){
                        if(!(bool)$meta['credit_rewarded']){
                            $this->ci->db->where('userId',$data['order']['id_user'])->update('siteUsers_extend',[
                                'credit'=>((int)$user['credit']+(int)$meta['credits']),
                            ]);
                            $meta['credit_rewarded'] = true;
                            $this->ci->db->where('order_id',$data['order']['id_order'])->update('order_payments',[
                                'order_meta'=>json_encode($meta),
                            ]);
                        }
                    }
                }

                // please update the order status in your system
                break;
            case '13':
                //	on hold
                $errorMessage = 'The transaction is on hold, additional checking is needed!';
                $r = [
                        'error_message'=>$errorMessage,
                        'cod_eroare'=>$X_RESPONSE_CODE,
                        'po_status' => 'on_hold',
                        'order_refference' => $data['order']['id_order'],
                        'authorization_response' => $authorization_response
                         ];

                $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'Credits PlatiOnline',$r);

                //13 = 1 code Pending payment
                $this->ci->db->where('order_id',$data['order']['id_order'])->update('order_payments',[
                                                    'order_status'=>1,
                                                    'payment_reg_date'=>date('Y-m-d H:i:s')
                                                ]);
                // please update the order status in your system
                break;
            case '8':
                //	declined
                $errorMessage = 'The transaction was declined! Reason: ' . $po->get_xml_tag_content($authorization_response, 'X_RESPONSE_REASON_TEXT') . '.';
                $r = [
                        'error_message'=>$errorMessage,
                        'cod_eroare'=>$X_RESPONSE_CODE,
                        'po_status' => 'declined',
                        'order_refference' => $data['order']['id_order'],
                        'authorization_response' => $authorization_response
                         ];

                $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'Credits PlatiOnline',$r);

                //8 = 5 code Canceled
                $this->ci->db->where('order_id',$data['order']['id_order'])->update('order_payments',[
                                                    'order_status'=>5,
                                                    'payment_reg_date'=>date('Y-m-d H:i:s')
                                                ]);
                // please update the order status in your system
                break;
            case '10';
                //	error
                $errorMessage = 'An error was encountered in authorization process';
                $r = [
                        'error_message'=>$errorMessage,
                        'cod_eroare'=>$X_RESPONSE_CODE,
                        'po_status' => 'error',
                        'order_refference' => $data['order']['id_order'],
                        'authorization_response' => $authorization_response
                         ];

                $this->ci->orders_manager_m->regPaymentResponse($data['order']['id_order'],'Credits PlatiOnline',$r);

                //8 = 5 code Canceled  Error
                $this->ci->db->where('order_id',$data['order']['id_order'])->update('order_payments',[
                                                    'order_status'=>5,
                                                    'payment_reg_date'=>date('Y-m-d H:i:s')
                                                ]);
                // please update the order status in your system
                break;
        }
    }
}
