<?php
  /*Makes call to authorize API. Validates credit card information and updates purchase information.*/
  include_once("CUserSession.php");
	include_once("CProject.php");
	include_once('helper.php');
	include_once("CUtil.php");
  include_once("CPurchase.php");

  require 'vendor/autoload.php';

  use net\authorize\api\contract\v1 as AnetAPI;
  use net\authorize\api\controller as AnetController;

  define("AUTHORIZENET_LOG_FILE", "phplog");

function chargeCreditCard($code, $card, $expdate)
{
    /* Create a merchantAuthenticationType object with authentication details
       retrieved from the constants file */
      
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    $merchantAuthentication->setName(\SampleCode\Constants::MERCHANT_LOGIN_ID);
    $merchantAuthentication->setTransactionKey(\SampleCode\Constants::MERCHANT_TRANSACTION_KEY);
      
    $billing = getpurchaseinfo();

    $billing = $billing[0];  
    // Set the transaction's refId
    $refId = $billing[0];

    //Create the payment data for a credit card
    $creditCard = new AnetAPI\CreditCardType();
    $creditCard->setCardNumber($card);
    $creditCard->setExpirationDate($expdate);
    $creditCard->setCardCode($code);
    $paymentOne = new AnetAPI\PaymentType();
    $paymentOne->setCreditCard($creditCard);

    $order = new AnetAPI\OrderType();
    $order->setDescription($billing[0]);

    // Set the customer's Bill To address
    $customerAddress = new AnetAPI\CustomerAddressType();
    $customerAddress->setFirstName($billing['firstname']);
    $customerAddress->setLastName($billing['lastname']);
    //$customerAddress->setCompany("Souveniropolis");
    $customerAddress->setAddress($billing['address']);
    $customerAddress->setCity($billing['city']);
    $customerAddress->setState($billing['state']);
    $customerAddress->setZip($billing['zipcode']);
    $customerAddress->setCountry($billing['country']);

    // Set the customer's identifying information
    $customerData = new AnetAPI\CustomerDataType();
    $customerData->setType("individual");
    $customerData->setId($_SESSION['user']->_id);
    $customerData->setEmail($billing['email']);

    //Add values for transaction settings
    $duplicateWindowSetting = new AnetAPI\SettingType();
    $duplicateWindowSetting->setSettingName("duplicateWindow");
    $duplicateWindowSetting->setSettingValue("600");

    // Create a TransactionRequestType object
    $transactionRequestType = new AnetAPI\TransactionRequestType();
    $transactionRequestType->setTransactionType( "authCaptureTransaction"); 
    $transactionRequestType->setAmount($billing['order_amount']);
    $transactionRequestType->setOrder($order);
    $transactionRequestType->setPayment($paymentOne);
    $transactionRequestType->setBillTo($customerAddress);
    $transactionRequestType->setCustomer($customerData);
    $transactionRequestType->addToTransactionSettings($duplicateWindowSetting);

    $request = new AnetAPI\CreateTransactionRequest();
    $request->setMerchantAuthentication($merchantAuthentication);
    $request->setRefId( $refId);
    $request->setTransactionRequest( $transactionRequestType);

    $controller = new AnetController\CreateTransactionController($request);
    $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);
    
    $ret = array();

    if ($response != null)
    {
      if($response->getMessages()->getResultCode() == \SampleCode\Constants::RESPONSE_OK)
      {
        $tresponse = $response->getTransactionResponse();
        
        if ($tresponse != null && $tresponse->getMessages() != null)   
        {
          /*get the response code and update order table, billing table and transaction table*/
          $ret['response_code'] = $tresponse->getResponseCode();
          $ret['description']   = $tresponse->getMessages()[0]->getDescription();
          $ret['auth_code']     = $tresponse->getAuthCode();
          $ret['trans_id']      = $tresponse->getTransId();
          $ret['code']          = $tresponse->getMessages()[0]->getCode();
          $ret['billed_amount']        = $billing['order_amount']; 
          $result = updatetransaction($ret);
          if(!$result['response']){
            $ret['response_code'] = 0;
            $ret['description'] = $result['message'];
          }

         

          return $ret;
          // echo " Transaction Response Code : " . $tresponse->getResponseCode() . "\n";
          // echo " Successfully created an authCapture transaction with Auth Code : " . $tresponse->getAuthCode() . "\n";
          // echo " Transaction ID : " . $tresponse->getTransId() . "\n";
          // echo " Code : " . $tresponse->getMessages()[0]->getCode() . "\n"; 
          // echo " Description : " . $tresponse->getMessages()[0]->getDescription() . "\n";
        }
        else
        { 
          $ret['description'] = "Transaction Failed";
          // echo "Transaction Failed \n";
          if($tresponse->getErrors() != null)
          {
            $ret['response_code']  =  $tresponse->getErrors()[0]->getErrorCode();
            $ret['err_message']    =  $tresponse->getErrors()[0]->getErrorText();
           
            // echo " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
            // echo " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";            
          }
        }
      }
      else
      {
        $ret['description'] = "Transaction Failed";
        // echo "Transaction Failed \n";
        $tresponse = $response->getTransactionResponse();
        
        if($tresponse != null && $tresponse->getErrors() != null)
        {
          $ret['response_code']  =  $tresponse->getErrors()[0]->getErrorCode();
          $ret['err_message']    =  $tresponse->getErrors()[0]->getErrorText();
          
          // echo " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
          // echo " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";                      
        }
        else
        {
          $ret['response_code']  =  $tresponse->getErrors()[0]->getErrorCode();
          $ret['err_message']    =  $tresponse->getErrors()[0]->getErrorText();
         
         // echo " Error code  : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
         // echo " Error message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
        }
      }      
    }
    else
    {
      $ret['description'] = "No response returned";
      
      //echo  "No response returned \n";
    }

    return $ret;
  }

  function validatedata($data){
    if(!empty($data['code']) && !empty($data['card']) && !empty($data['expdate'])){
      $visa = "/^4[0-9]{12}(?:[0-9]{3})?$/";
      $master = "/^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/";
      $discover = "/^(?:6(?:011|5[0-9]{2})(?:[0-9]{12}))$/";
      $americanexpress = "/^(?:3[47][0-9]{13})$/";
      $maestro = "/^(?:(?:5[0678]'\''\'d'\''\'d|6304|6390|67'\''\'d'\''\'d)'\''\'d{8,15})$/";

      $ccv = "/^[0-9]{3,4}$/";
      $expdate = "/^20[0-9]{2}-(0[1-9]|10|11|12)$/";
      $validate['response'] = true;
      $validate['message'] = "success";
      
      if(preg_match($visa, $data['card']) || preg_match($master, $data['card']) || preg_match($discover, $data['card']) || preg_match($americanexpress, $data['card']) || preg_match($maestro, $data['card'])) {
      }else{
        $validate['response'] = false;
        $validate['message'] = "card details invalid";
        return $validate;
      }
      if(preg_match($ccv, $data['code'])){
      }else{
        $validate['response'] = false;
        $validate['message'] = "code details invalid";
        return $validate;
      }
      if(preg_match($expdate, $data['expdate'])){
      }else{
        $validate['response'] = false;
        $validate['message'] = "date details invalid";
        return $validate;
      }
      return $validate;
    }else{
        $validate['response'] = false;
        $validate['message'] = "card details null";
        return $validate;
    }
  }

  // if(!defined('DONT_RUN_SAMPLES'))
  //     chargeCreditCard(\SampleCode\Constants::SAMPLE_AMOUNT);
?>