<?php
session_start();
require_once "main.php";
//Logger::configure('log4php.xml');
//$log = Logger::getLogger('ccpayinfo');
global $db;
$comz = $_SESSION['comnum'];
?>
<script>
        function setType(type)
        {
            var z=0;
            var x=document.forms["accinform"]["bamount"].value;
            if (x==0 || x==null || x=="") {
                alert("An amount is required");
                return false;
            }
            document.accinform.submitType.value = type;
        }
</script>
<?php
if ($_GET['submitType']=='payAdd') {
        $zpc1 = bill_get_pname($_SESSION['comnum']);
        $zpc = $zpc1['0']['id'];
        $zres = json_decode($_COOKIE['response']);
        $zrcode = $zres->responseCode;
        ?>
         <script>document.cookie = `response=""`;</script>
        <?php
        if ($zrcode = 1) {
            $zcid = $zres->customerId;
            $zta = $zres->totalAmount;
            $ztid = $zres->transId;
            $zaut = $zres->authorization;
        $res2 = bill_get_abalance(@$zcid);
        $zbal = $res2[0]['abalance'] - $zta;
        $test = bill_insert_payment($_SESSION['comnum'], $zcid, $zpc, $zta, $ztid, $zaut, 'cc', $zbal);

        if ($test>1) {
            //$log->info($_GET['submitType'].' - user = '.$_SESSION['user'].' - '.$_SESSION['comnum']);
?>
            <script>alert('Transaction Completed Sucessfully');location.reload(true);</script>
<?php
        } else {
            //$log->warn($_GET['submitType'].' - user = '.$_SESSION['user'].' - '.$_SESSION['comnum']);
?>
            <script>alert("There was a database error, please check account balance and payment history. Please include the following in all communications with WtrFlw Services LLC.  Error $ccpayinfo33");</script>';
<?php
        }
}
} else if ($_GET['submitType']=='gethosted') {
        $company1z = bill_get_company($_SESSION['comnum']);
        $res4 = bill_get_customer($_SESSION['comnum'], $_GET['cid']);
        $names1 = explode(" ", $res4['0']['name']);
$xmlStr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<getHostedPaymentPageRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
    <merchantAuthentication></merchantAuthentication>
    <transactionRequest>
        <transactionType>authCaptureTransaction</transactionType>
    </transactionRequest>
    <hostedPaymentSettings>
        <setting>
            <settingName>hostedPaymentButtonOptions</settingName>
            <settingValue>{"text": "Pay"}</settingValue>
        </setting>
        <setting>
            <settingName>hostedPaymentReturnOptions</settingName>
        </setting>
        <setting>
            <settingName>hostedPaymentOrderOptions</settingName>
            <settingValue>{"show": false}</settingValue>
        </setting>
        <setting>
            <settingName>hostedPaymentPaymentOptions</settingName>
            <settingValue>{"cardCodeRequired": true}</settingValue>
        </setting>
        <setting>
            <settingName>hostedPaymentBillingAddressOptions</settingName>
            <settingValue>{"show": true, "required":true}</settingValue>
        </setting>
        <setting>
            <settingName>hostedPaymentShippingAddressOptions</settingName>
            <settingValue>{"show": false, "required":false}</settingValue>
        </setting>
        <setting>
            <settingName>hostedPaymentSecurityOptions</settingName>
            <settingValue>{"captcha": false}</settingValue>
        </setting>
        <setting>
            <settingName>hostedPaymentStyleOptions</settingName>
            <settingValue>{"bgColor": "green"}</settingValue>
        </setting>
        <setting>
            <settingName>hostedPaymentCustomerOptions</settingName>
            <settingValue>{"showEmail": true, "requiredEmail":true}</settingValue>
        </setting>
        <setting>
            <settingName>hostedPaymentIFrameCommunicatorUrl</settingName>
            <settingValue>{"url": "https://wtrbill.com/bill/includes/IFrameCommunicator.html"}</settingValue>
        </setting>
    </hostedPaymentSettings>
</getHostedPaymentPageRequest>
XML;
$xml = simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOWARNING);
$xml->merchantAuthentication->addChild('name', @$company1z['0']['apiloginid']);
$xml->merchantAuthentication->addChild('transactionKey', @$company1z['0']['transactionkey']);
$xml->transactionRequest->addChild('amount', @$_GET['bamount']);
$xml->transactionRequest->addChild('profile');
$xml->transactionRequest->addChild('customer');
$xml->transactionRequest->addChild('billTo');
$xml->transactionRequest->profile->addChild('customerProfileId', @$res4['0']['profileid']);
$xml->transactionRequest->customer->addChild('id', @$_GET['cid']);
$xml->transactionRequest->customer->addChild('email', @$res4['0']['bill_email']);
$xml->transactionRequest->billTo->addChild('firstName', @$names1['0']);
$xml->transactionRequest->billTo->addChild('lastName', @$names1['1']);
$xml->transactionRequest->billTo->addChild('address', @$res4['0']['addr']);
$xml->transactionRequest->billTo->addChild('city', @$res4['0']['city']);
$xml->transactionRequest->billTo->addChild('state', @$res4['0']['state']);
$xml->transactionRequest->billTo->addChild('zip', @$res4['0']['zip']);
$xml->transactionRequest->billTo->addChild('country', 'US');

$retUrl = json_encode(array("showReceipt" => false , 'url' => "https://wtrbill.com/bill/includes/return.html", "urlText"=>"Return to site", "cancelUrl" => "https://wtrbill.com/includes/epayinfo.php", "cancelUrlText" => "Cancel" ), JSON_UNESCAPED_SLASHES);
$xml->hostedPaymentSettings->setting[1]->addChild('settingValue', $retUrl);
$url = "https://apitest.authorize.net/xml/v1/request.api";
//print_r($xml);
try {   //setting the curl parameters.
        $ch = curl_init();
    if (false === $ch) {
        throw new Exception('failed to initialize');
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
    // The following two curl SSL options are set to "false" for ease of development/debug purposes only.
    // Any code used in production should either remove these lines or set them to the appropriate
    // values to properly use secure connections for PCI-DSS compliance.
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    //for production, set value to true or 1
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);    //for production, set value to 2
    curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
    //curl_setopt($ch, CURLOPT_PROXY, 'userproxy.visa.com:80');
    $content = curl_exec($ch);
    $content = str_replace('xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"', '', $content);

    $hostedPaymentResponse = new SimpleXMLElement($content);
    //print_r($hostedPaymentResponse);
    if (false === $content) {
            throw new Exception(curl_error($ch), curl_errno($ch));
    }
    curl_close($ch);
} catch (Exception $e) {
        trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR);
}
?>
    <form method="post" action="https://test.authorize.net/payment/payment" id="formAuthorizeNetPopup" name="formAuthorizeNetPopup" target="iframeAuthorizeNet">
    <input type="hidden" id="token" name="token" value="<?php echo $hostedPaymentResponse->token ?>"/>
    </form>
    <button id="btnOpenAuthorizeNetPopup" hidden="hidden" onclick="AuthorizeNetPopup.openPopup()">Next Step</button>
    <button id="btnPostEPayment" hidden="hidden" onclick="dynamic_Select('includes/ccpayinfo.php', '#accinfo', 'payAdd', null,'0')">Post Payment Details to Account</button>
    <script>document.getElementById("btnOpenAuthorizeNetPopup").click();</script>
<?php
        }
?>