<?php
class Mobilpay
{
    private $CI;
    public $acc_uniq_key = '';

    public $server = 'sandbox';
    public $redirect_url = null;
    public function __construct(){
        $this->CI = & get_instance();
        require_once APPPATH.'/libraries/Mobilpay/Request/Abstract.php';
        require_once APPPATH.'/libraries/Mobilpay/Request/Card.php';
        require_once APPPATH.'/libraries/Mobilpay/Invoice.php';
        require_once APPPATH.'/libraries/Mobilpay/Address.php';
    }

    public $response = null;
    public $errors = null;
    public function _set_response($key,$id_order){
        $this->response[$key] = $id_order;

    }
    public function _set_error($code,$message){
        $this->errors[] = [
            'code'=>$code,
            'message'=>$message
        ];
    }
    public function get_response(){
        return $this->response;
    }
    public function get_errors(){
        return $this->errors;
    }

    public function gateway($data){
      //pre($data);

        if($this->redirect_url != null){ $success_url = $this->redirect_url; }else{ $success_url = base_url(); }

        $fname = '';
        $lname = '';
        if(!empty($data['user'])){
          $fname = $data['user']->firstname;
          $lname = $data['user']->lastname;
        }
        $passed_data = [
            'amount' => $data['invoice']->total,
            'orderId' => $data['invoiceid'],

            'billing_type' => 'company',
            'billing_first_name' =>   $fname,
            'billing_last_name' => $lname,
            'billing_address' => $data['invoice']->client->address,
            'billing_email' => $data['invoice']->client->organization_email,
            'billing_mobile_phone' => $data['invoice']->client->phonenumber,

            'shipping_type' => 'company',
            'shipping_first_name' =>   $fname,
            'shipping_last_name' => $lname,
            'shipping_address' => $data['invoice']->client->address,
            'shipping_email' => $data['invoice']->client->organization_email,
            'shipping_mobile_phone' => $data['invoice']->client->phonenumber,

            'redirect_url_success' => $success_url
        ];
        if($this->server == 'live'){
            $paymentUrl = 'https://secure.mobilpay.ro';
        }else if($this->server == 'sandbox'){
            $paymentUrl = 'http://sandboxsecure.mobilpay.ro';
        }
#for testing purposes, all payment requests will be sent to the sandbox server. Once your account will be active you must switch back to the live server https://secure.mobilpay.ro
#in order to display the payment form in a different language, simply add the language identifier to the end of the paymentUrl, i.e https://secure.mobilpay.ro/en for English
//$paymentUrl = 'https://secure.mobilpay.ro';
// this is the path on your server to the public certificate. You may download this from Admin -> Conturi de comerciant -> Detalii -> Setari securitate
$x509FilePath 	= FCPATH.'uploads/company/'.$this->server.'.'.$this->acc_uniq_key.'.public.cer';
if(!is_file($x509FilePath)){
  die('Certificate not found.');
}

try
{
	srand((double) microtime() * 1000000);
	$objPmReqCard 						= new Mobilpay_Payment_Request_Card();
	#merchant account signature - generated by mobilpay.ro for every merchant account
	#semnatura contului de comerciant - mergi pe www.mobilpay.ro Admin -> Conturi de comerciant -> Detalii -> Setari securitate
	$objPmReqCard->signature 			= $this->acc_uniq_key;
	#you should assign here the transaction ID registered by your application for this commercial operation
	#order_id should be unique for a merchant account

	$objPmReqCard->orderId 				= ($passed_data['orderId']?$passed_data['orderId']:md5(uniqid(rand())));
	#below is where mobilPay will send the payment result. This URL will always be called first; mandatory
	$objPmReqCard->confirmUrl 			= $this->confirm_url;
	#below is where mobilPay redirects the client once the payment process is finished. Not to be mistaken for a "successURL" nor "cancelURL"; mandatory
	if($passed_data['redirect_url_success']){
      $objPmReqCard->returnUrl 			= $passed_data['redirect_url_success'];
  }else{
      $objPmReqCard->returnUrl 			= base_url();
  }



	#detalii cu privire la plata: moneda, suma, descrierea
	#payment details: currency, amount, description
	$objPmReqCard->invoice = new Mobilpay_Payment_Invoice();
	#payment currency in ISO Code format; permitted values are RON, EUR, USD, MDL; please note that unless you have mobilPay permission to
	#process a currency different from RON, a currency exchange will occur from your currency to RON, using the official BNR exchange rate from that moment
	#and the customer will be presented with the payment amount in a dual currency in the payment page, i.e N.NN RON (e.ee EUR)
	$objPmReqCard->invoice->currency	= 'RON';
	$objPmReqCard->invoice->amount		= $passed_data['amount'];
	#available installments number; if this parameter is present, only its value(s) will be available
	//$objPmReqCard->invoice->installments= '2,3';
	#selected installments number; its value should be within the available installments defined above
	//$objPmReqCard->invoice->selectedInstallments= '3';
  //platile ulterioare vor contine in request si informatiile despre token. Prima plata nu va contine linia de mai jos.
  $objPmReqCard->invoice->tokenId = 'token_id';
	$objPmReqCard->invoice->details		= $data['invoice_details'];

	#detalii cu privire la adresa posesorului cardului
	#details on the cardholder address (optional)
	$billingAddress 				= new Mobilpay_Payment_Address();
	$billingAddress->type			= $passed_data['billing_type']; //should be "person"
	$billingAddress->firstName		= $passed_data['billing_first_name'];
	$billingAddress->lastName		= $passed_data['billing_last_name'];
	$billingAddress->address		= $passed_data['billing_address'];
	$billingAddress->email			= $passed_data['billing_email'];
	$billingAddress->mobilePhone		= $passed_data['billing_mobile_phone'];
	$objPmReqCard->invoice->setBillingAddress($billingAddress);

	#detalii cu privire la adresa de livrare
	#details on the shipping address
	$shippingAddress 				= new Mobilpay_Payment_Address();
	$shippingAddress->type			= $passed_data['shipping_type'];
	$shippingAddress->firstName		= $passed_data['shipping_first_name'];
	$shippingAddress->lastName		= $passed_data['shipping_last_name'];
	$shippingAddress->address		= $passed_data['shipping_address'];
	$shippingAddress->email			= $passed_data['shipping_email'];
	$shippingAddress->mobilePhone		= $passed_data['shipping_mobile_phone'];
	$objPmReqCard->invoice->setShippingAddress($shippingAddress);

	#uncomment the line below in order to see the content of the request
	//echo "<pre>";print_r($objPmReqCard);echo "</pre>";
	$objPmReqCard->encrypt($x509FilePath);
}
catch(Exception $e)
{
}
?>
<div class="full-width main-archive">
	<div class="container site-container boxcontainer frm-submit-project">
            <div id="content" class="row site-content page-credit ">
                <div class="col-md-12 line-item credit-info">
<?php //if(!($e instanceof Exception)):?>
<p>
	<form name="frmPaymentRedirect" method="post" action="<?php echo $paymentUrl;?>">
	<input type="hidden" name="env_key" value="<?php echo $objPmReqCard->getEnvKey();?>"/>
	<input type="hidden" name="data" value="<?php echo $objPmReqCard->getEncData();?>"/>
	<p>
		Vei redirectat catre pagina de plati securizata a mobilpay.ro
	</p>
	<p>
		Pentru a continua apasa <input type="image" src="<?= site_url(); ?>/assets/images/mobilpay.jpg" />
	</p>
	</form>
</p>

<script type="text/javascript" language="javascript">
	window.setTimeout(document.frmPaymentRedirect.submit(), 5000);
</script>
<?php //else: ?>
<p><strong><?php //echo $e->getMessage();?></strong></p>
<?php //endif; ?>
<br/>
<br/>
                </div>
            </div>
        </div>
</div>

    <?php
    }

    public function response(){
        require_once APPPATH.'/libraries/Mobilpay/Request/Abstract.php';
        require_once APPPATH.'/libraries/Mobilpay/Request/Card.php';
        require_once APPPATH.'/libraries/Mobilpay/Request/Notify.php';
        require_once APPPATH.'/libraries/Mobilpay/Invoice.php';
        require_once APPPATH.'/libraries/Mobilpay/Address.php';


        $errorCode 		= 0;
        $errorType		= Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_NONE;
        $errorMessage	= '';

        if (strcasecmp($_SERVER['REQUEST_METHOD'], 'post') == 0)
        {
                if(isset($_POST['env_key']) && isset($_POST['data']))
                {
                  //$this->_set_response('order_id',$objPmReq->orderId);
                        #calea catre cheia privata
                        #cheia privata este generata de mobilpay, accesibil in Admin -> Conturi de comerciant -> Detalii -> Setari securitate
                        $privateKeyFilePath = FCPATH.'uploads/company/'.$this->server.'.'.$this->acc_uniq_key.'private.key';
                        if(!is_file($privateKeyFilePath)){
                          die('Security key not found at '.$privateKeyFilePath.'.');
                        }
                        try
                        {
                        $objPmReq = Mobilpay_Payment_Request_Abstract::factoryFromEncrypted($_POST['env_key'], $_POST['data'], $privateKeyFilePath);


                        #uncomment the line below in order to see the content of the request
                        //print_r($objPmReq);
                        $rrn = $objPmReq->objPmNotify->rrn;
                        // action = status only if the associated error code is zero
                        if ($objPmReq->objPmNotify->errorCode == 0) {


                          $this->_set_response('order_id',$objPmReq->orderId);
                          $this->_set_error($objPmReq->objPmNotify->errorCode,$objPmReq->objPmNotify->errorMessage);
                          $this->_set_response('status',$objPmReq->objPmNotify->action);

                                switch($objPmReq->objPmNotify->action)
                                {
                                        #orice action este insotit de un cod de eroare si de un mesaj de eroare. Acestea pot fi citite folosind $cod_eroare = $objPmReq->objPmNotify->errorCode; respectiv $mesaj_eroare = $objPmReq->objPmNotify->errorMessage;
                                        #pentru a identifica ID-ul comenzii pentru care primim rezultatul platii folosim $id_comanda = $objPmReq->orderId;
                                case 'confirmed':
                                        #cand action este confirmed avem certitudinea ca banii au plecat din contul posesorului de card si facem update al starii comenzii si livrarea produsului
                                        //update DB, SET status = "confirmed/captured"
                                        $id_comanda = $objPmReq->orderId;
                                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
                                        $cod_eroare = $objPmReq->objPmNotify->errorCode;
                                        /*
                                        $this->_set_response('order_id',$objPmReq->orderId);
                                        $this->_set_error($objPmReq->objPmNotify->errorCode,$objPmReq->objPmNotify->errorMessage);
                                        $this->_set_response('status','confirmed');
                                        */
                                    break;
                                        case 'confirmed_pending':
                                         #cand action este confirmed_pending inseamna ca tranzactia este in curs de verificare antifrauda. Nu facem livrare/expediere. In urma trecerii de aceasta verificare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
                                        //update DB, SET status = "pending"
                                        $id_comanda = $objPmReq->orderId;
                                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
                                        $cod_eroare = $objPmReq->objPmNotify->errorCode;
                                    break;
                                        case 'paid_pending':
                                        #cand action este paid_pending inseamna ca tranzactia este in curs de verificare. Nu facem livrare/expediere. In urma trecerii de aceasta verificare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
                                        //update DB, SET status = "pending"
                                        $id_comanda = $objPmReq->orderId;
                                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
                                        $cod_eroare = $objPmReq->objPmNotify->errorCode;
                                    break;
                                        case 'paid':
                                         #cand action este paid inseamna ca tranzactia este in curs de procesare. Nu facem livrare/expediere. In urma trecerii de aceasta procesare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
                                        //update DB, SET status = "open/preauthorized"
                                        $id_comanda = $objPmReq->orderId;
                                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
                                        $cod_eroare = $objPmReq->objPmNotify->errorCode;
                                    break;
                                        case 'canceled':
                                         #cand action este canceled inseamna ca tranzactia este anulata. Nu facem livrare/expediere.
                                        //update DB, SET status = "canceled"
                                        $id_comanda = $objPmReq->orderId;
                                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
                                        $cod_eroare = $objPmReq->objPmNotify->errorCode;
                                    break;
                                        case 'credit':
                                        #cand action este credit inseamna ca banii sunt returnati posesorului de card. Daca s-a facut deja livrare, aceasta trebuie oprita sau facut un reverse.
                                        //update DB, SET status = "refunded"
                                        $id_comanda = $objPmReq->orderId;
                                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
                                        $cod_eroare = $objPmReq->objPmNotify->errorCode;
                                    break;
                                default:
                                    $errorType		= Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
                                    $errorCode 		= Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_ACTION;
                                    $errorMessage 	= 'mobilpay_refference_action paramaters is invalid';
                                    break;
                                }
                        }
                        else {
                        //update DB, SET status = "rejected"
                        $errorMessage = $objPmReq->objPmNotify->errorMessage;
                                }
                        }
                        catch(Exception $e)
                        {
                                $errorType 		= Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_TEMPORARY;
                                $errorCode		= $e->getCode();
                                $errorMessage 	= $e->getMessage();
                        }
                }
                else
                {
                        $errorType 		= Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
                        $errorCode		= Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_POST_PARAMETERS;
                        $errorMessage 	= 'mobilpay.ro posted invalid parameters';
                }
        }
        else
        {
                $errorType 		= Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
                $errorCode		= Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_POST_METHOD;
                $errorMessage 	= 'invalid request metod for payment confirmation';
        }

        header('Content-type: application/xml');
        echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
        if($errorCode == 0)
        {
                echo "<crc>{$errorMessage}</crc>";
        }
        else
        {
                echo "<crc error_type=\"{$errorType}\" error_code=\"{$errorCode}\">{$errorMessage}</crc>";
        }

    }



}
