<?php
class Euplatesc{

    private $ci;
    private $mid = '';
    private $key = '';

    //test 44840994734    b70ef989197d8e0a1af6b9ce77dc8de5cb29c129
    //live terminal 3I738504    X   X


    public function __construct(){
        $this->ci = & get_instance();
    }
    public function set_mid($mid){
      $this->mid = $mid;
    }
    public function set_key($key){
      $this->key = $key;
    }
    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 payment_form($data){
        $dataAll = array(
            'amount'      => $data['invoice']->total,
            'curr'        => 'RON',
            'invoice_id'  => $data['invoiceid'],
            'order_desc'  => $data['invoice_details'],
            //va rog sa nu modificati urmatoarele 3 randuri
            'merch_id'    => $this->mid,  // nu modificati
            'timestamp'   => gmdate("YmdHis"),// nu modificati
            'nonce'       => md5(microtime() . mt_rand()), //nu modificati
        );

        $dataAll['fp_hash'] = strtoupper($this->euplatesc_mac($dataAll,$this->key));


        $data['total'] = $data['invoice']->total;
        $data['curr'] = 'RON';
        $data['cart_order_id'] = $data['invoiceid'];
        $data['order_desc'] = $data['invoice_details'];
        $data['sid'] = $dataAll['merch_id'];
        $data['timestamp'] = $dataAll['timestamp'];
        $data['nonce'] = $dataAll['nonce'];
        $data['fp_hash'] = $dataAll['fp_hash'];
        //$data['shipping'] = $shippingcost;

        //if($data['invoice_company'] == 0){
          /*
            $dataBill = array(
                'fname'	   => $data['firstName'],      // nume
                'lname'	   => $data['lastName'],   // prenume
                'company'  => '',   // firma
                'country'  => 'Romania',      // tara
                'city'	   => $data['person_city'],      // oras
                'add'	   => $data['person_street_name'],    // adresa
                'email'	   => $data['userEmail'],     // email
                'phone'	   => $data['phone'],   // telefon
                'fax'	   => '',       // fax
            );

            $dataShip = array(
                'sfname'	   => $data['firstName'],      // nume
                'slname'	   => $data['lastName'],   // prenume
                'scompany'  => '',   // firma
                'scountry'  => 'Romania',      // tara
                'scity'	   => $data['person_city'],      // oras
                'sadd'	   => $data['person_street_name'],    // adresa
                'semail'	   => $data['userEmail'],     // email
                'sphone'	   => $data['phone'],   // telefon
                'sfax'	   => '',       // fax
            );*/
        //}else{
            $fname = '';
            $lname = '';
            if(!empty($data['user'])){
              $fname = $data['user']->firstname;
              $lname = $data['user']->lastname;
            }
            $dataBill = array(
                'fname'	   => $fname,
                'lname'	   => $lname,
                'country'  => $data['billing_country'],
                'company'  => $data['invoice']->client->company,
                'city'	   => $data['invoice']->client->billing_city,
                'add'	   => $data['invoice']->client->billing_street,
                'email'	   => $data['invoice']->client->organization_email,
                'phone'	   => $data['invoice']->client->phonenumber,
                'fax'	   => '',
            );

            $dataShip = array(
                'sfname'	   => $fname,
                'slname'	   => $lname,
                'scountry'  => $data['shipping_country'],
                'scompany'  => $data['invoice']->client->company,
                'scity'	   => $data['invoice']->client->shipping_city,
                'sadd'	   => $data['invoice']->client->shipping_street,
                'semail'	   => $data['invoice']->client->organization_email,
                'sphone'	   => $data['invoice']->client->phonenumber,
                'sfax'	   => '',
            );
        //}

        $data['action'] = 'https://secure.euplatesc.ro/tdsprocess/tranzactd.php';
        $data = array_merge($dataAll, $dataBill, $dataShip);
        $this->ci->load->view('euplatesc_from', $data);
    }
    public function response(){
        $zcrsp =  array (
        'amount'     => addslashes(trim(@$_POST['amount'])),  //original amount
        'curr'       => addslashes(trim(@$_POST['curr'])),    //original currency
        'invoice_id' => addslashes(trim(@$_POST['invoice_id'])),//original invoice id
        'ep_id'      => addslashes(trim(@$_POST['ep_id'])), //Euplatesc.ro unique id
        'merch_id'   => addslashes(trim(@$_POST['merch_id'])), //your merchant id
        'action'     => addslashes(trim(@$_POST['action'])), // if action ==0 transaction ok
        'message'    => addslashes(trim(@$_POST['message'])),// transaction responce message
        'approval'   => addslashes(trim(@$_POST['approval'])),// if action!=0 empty
        'timestamp'  => addslashes(trim(@$_POST['timestamp'])),// meesage timestamp
        'nonce'      => addslashes(trim(@$_POST['nonce'])),
        );

        $zcrsp['fp_hash'] = strtoupper($this->euplatesc_mac($zcrsp, $this->key));

        $fp_hash=addslashes(trim(@$_POST['fp_hash']));

        $this->_set_response('order_id',addslashes(trim(@$_POST['invoice_id'])));



      	if($zcrsp['fp_hash']===$fp_hash)	{
      		if($zcrsp['action']=="0") {
              $this->_set_response('status','success');
      		}
      		else {
              $this->_set_error('failed', "Tranzaction failed" . $zcrsp['message']);
              $this->_set_response('status','failed');
      		}
      	}else {
              $this->_set_error('failed', "Invalid signature");
              $this->_set_response('status','failed');
      	}

        $this->ci->db->insert('log_ep',[
            'entry_date'=>date('Y-m-d H:i:s'),
            'amount'=>addslashes(trim(@$_POST['amount'])),
            'curr'=>addslashes(trim(@$_POST['curr'])),
            'invoice_id'=>addslashes(trim(@$_POST['invoice_id'])),
            'ep_id'=>addslashes(trim(@$_POST['ep_id'])),
            'merch_id'=>addslashes(trim(@$_POST['merch_id'])),
            'action'=>addslashes(trim(@$_POST['action'])),
            'message'=>addslashes(trim(@$_POST['message'])),
            'approval'=>addslashes(trim(@$_POST['approval'])),
            'timestamp'=>addslashes(trim(@$_POST['timestamp'])),
            'nonce'=>addslashes(trim(@$_POST['nonce'])),
        ]);




    }





    function hmacsha1($key,$data) {
       $blocksize = 64;
       $hashfunc  = 'md5';

       if(strlen($key) > $blocksize)
         $key = pack('H*', $hashfunc($key));

       $key  = str_pad($key, $blocksize, chr(0x00));
       $ipad = str_repeat(chr(0x36), $blocksize);
       $opad = str_repeat(chr(0x5c), $blocksize);

       $hmac = pack('H*', $hashfunc(($key ^ $opad) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));
       return bin2hex($hmac);
    }
    // ===========================================================================================
    function euplatesc_mac($data, $key = NULL)
    {
      $str = NULL;

      foreach($data as $d)
      {
       	if($d === NULL || strlen($d) == 0)
      	  $str .= '-'; // valorile nule sunt inlocuite cu -
      	else
      	  $str .= strlen($d) . $d;
      }

      $key = pack('H*', $key);

      return $this->hmacsha1($key, $str);
    }




}
