/**
 * This functions send a PAYMENT_CHANGE request with the sub operation goodwill
 * to the RatePAY API and saves all necessary informations in the DB
 * @param string $oID
 * @param string $paymentType
 *
 * @return array
 */
function voucherRequest($oID, $paymentType)
{
    $cab = new pi_ratepay_rechnung();
    if (isset($_POST)) {
        $operation = 'PAYMENT_CHANGE';
        if ($paymentType == "pi_ratepay_rechnung") {
            $pi_ratepay = new pi_ratepay_rechnung();
            $pi_table_prefix = 'pi_ratepay_rechnung';
            $pi_payment_type = 'INVOICE';
        } else {
            $pi_ratepay = new pi_ratepay_rate();
            $pi_table_prefix = 'pi_ratepay_rate';
            $pi_payment_type = 'INSTALLMENT';
        }
        $profileId = $pi_ratepay->profileId;
        $securityCode = $pi_ratepay->securityCode;
        $systemId = $_SERVER['SERVER_ADDR'];
        $query = xtc_db_query("select customers_id,customers_country,billing_country,delivery_country from orders where orders_id = '" . xtc_db_input($oID) . "'");
        $customerIdArray = xtc_db_fetch_array($query);
        $customerId = $customerIdArray['customers_id'];
        $subOperation = 'credit';
        $query = xtc_db_query("select customers_gender, date_format(customers_dob, '%Y-%m-%d') as customers_dob, customers_email_address, customers_telephone from " . TABLE_CUSTOMERS . " where customers_id ='" . xtc_db_input($customerId) . "'");
        $customerXTC = xtc_db_fetch_array($query);
        $email = $customerXTC['customers_email_address'];
        $query = xtc_db_query("select transaction_id, transaction_short_id from " . $pi_table_prefix . "_orders where order_number = '" . xtc_db_input($oID) . "'");
        $transactionArray = xtc_db_fetch_array($query);
        $query = xtc_db_query("select * from orders a, orders_total b where a.orders_id = '" . xtc_db_input($oID) . "' and a.orders_id = b.orders_id and class = 'ot_total'");
        $order = xtc_db_fetch_array($query);
        if (isset($_POST['voucherAmount'])) {
            if (preg_match("/^[0-9]{1,4}\$/", $_POST['voucherAmount'])) {
                $piRatepayVoucher = $_POST['voucherAmount'];
                if (isset($_POST['voucherAmountKomma']) && $_POST['voucherAmountKomma'] != '') {
                    if (preg_match("/^[0-9]{2}\$/", $_POST['voucherAmountKomma'])) {
                        $piRatepayVoucher = $piRatepayVoucher . "." . $_POST['voucherAmountKomma'];
                    } else {
                        if (preg_match("/^[0-9]{1}\$/", $_POST['voucherAmountKomma'])) {
                            $piRatepayVoucher = $piRatepayVoucher . "." . $_POST['voucherAmountKomma'] . "0";
                        } else {
                            $piRatepayVoucher = $piRatepayVoucher . ".00";
                            $message = PI_RATEPAY_ERRORVOUCHER;
                            return array('result' => 'ERROR', 'message' => $message);
                        }
                    }
                } else {
                    $piRatepayVoucher = $piRatepayVoucher . ".00";
                    $message = PI_RATEPAY_ERRORVOUCHER;
                    return array('result' => 'ERROR', 'message' => $message);
                }
                if ($piRatepayVoucher > $order['value']) {
                    $message = PI_RATEPAY_ERRORVOUCHER;
                    return array('result' => 'ERROR', 'message' => $message);
                } else {
                    $piRatepayVoucher = $piRatepayVoucher * -1;
                    $ratepay = new Ratepay_XML();
                    $ratepay->live = $pi_ratepay->testOrLive();
                    $request = $ratepay->getXMLObject();
                    $request->addChild('head');
                    $head = $request->{'head'};
                    $head->addChild('system-id', $systemId);
                    $head->addChild('transaction-id', $transactionArray['transaction_id']);
                    $head->addChild('transaction-short-id', $transactionArray['transaction_short_id']);
                    $operation = $head->addChild('operation', $operation);
                    $operation->addAttribute('subtype', $subOperation);
                    $credential = $head->addChild('credential');
                    $credential->addChild('profile-id', $profileId);
                    $credential->addChild('securitycode', $securityCode);
                    $external = $head->addChild('external');
                    $external->addChild('order-id', $oID);
                    $content = $request->addChild('content');
                    $content->addChild('customer');
                    if (strtoupper($customerXTC['customers_gender']) == "F") {
                        $gender = "F";
                    } else {
                        if (strtoupper($customerXTC['customers_gender']) == "M") {
                            $gender = "M";
                        } else {
                            $gender = "U";
                        }
                    }
                    $customer = $content->customer;
                    $customer->addCDataChild('first-name', removeSpecialChars(utf8_encode($order['customers_firstname'])));
                    $customer->addCDataChild('last-name', removeSpecialChars(utf8_encode($order['customers_lastname'])));
                    $customer->addChild('gender', $gender);
                    $customer->addChild('date-of-birth', (string) utf8_encode($customerXTC['customers_dob']));
                    $customer->addChild('contacts');
                    $contacts = $customer->contacts;
                    $contacts->addChild('email', utf8_encode($email));
                    $contacts->addChild('phone');
                    $phone = $contacts->phone;
                    $phone->addChild('direct-dial', utf8_encode($customerXTC['customers_telephone']));
                    $customer->addChild('addresses');
                    $addresses = $customer->addresses;
                    $addresses->addChild('address');
                    $addresses->addChild('address');
                    $billingAddress = $addresses->address[0];
                    $shippingAddress = $addresses->address[1];
                    $billingAddress->addAttribute('type', 'BILLING');
                    $shippingAddress->addAttribute('type', 'DELIVERY');
                    $billingAddress->addCDataChild('street', removeSpecialChars(utf8_encode($order['delivery_street_address'])));
                    $billingAddress->addChild('zip-code', utf8_encode($order['delivery_postcode']));
                    $billingAddress->addCDataChild('city', removeSpecialChars(utf8_encode($order['delivery_city'])));
                    $billingAddress->addChild('country-code', utf8_encode($order['delivery_country_iso_code_2']));
                    $shippingAddress->addCDataChild('street', removeSpecialChars(utf8_encode($order['delivery_street_address'])));
                    $shippingAddress->addChild('zip-code', utf8_encode($order['delivery_postcode']));
                    $shippingAddress->addCDataChild('city', removeSpecialChars(utf8_encode($order['delivery_city'])));
                    $shippingAddress->addChild('country-code', utf8_encode($order['delivery_country_iso_code_2']));
                    $customer->addChild('nationality', utf8_encode($order['delivery_country_iso_code_2']));
                    $customer->addChild('customer-allow-credit-inquiry', 'yes');
                    $shoppingBasket = $content->addChild('shopping-basket');
                    $shoppingBasket->addAttribute('currency', 'EUR');
                    $items = $shoppingBasket->addChild('items');
                    $sql = "select * from " . $pi_table_prefix . "_orderdetails a left join orders_products b on b.orders_id = a.order_number and a.article_number = b.orders_products_id where  a.order_number = '" . xtc_db_input($oID) . "' and  article_number != ''";
                    $query = xtc_db_query($sql);
                    $i = 0;
                    $shippingCost = 0;
                    $couponTax = 0;
                    while ($mItem = xtc_db_fetch_array($query)) {
                        $qty = $mItem['ordered'] - $mItem['returned'] - $mItem['canceled'];
                        if ($mItem['article_name'] != 'pi-Merchant-Voucher' && $mItem['article_number'] != 'SHIPPING' && $mItem['article_number'] != 'DISCOUNT' && $mItem['article_number'] != 'COUPON') {
                            $items->addCDataChild('item', removeSpecialChars(utf8_encode($mItem['article_name'])));
                            $items->item[$i]->addAttribute('article-number', $mItem['products_id']);
                            $items->item[$i]->addAttribute('quantity', $qty);
                            $items->item[$i]->addAttribute('unit-price', number_format($mItem['products_price'] / (100 + $mItem['products_tax']) * 100, 2, '.', ''));
                            $items->item[$i]->addAttribute('total-price', number_format($mItem['products_price'] / (100 + $mItem['products_tax']) * 100 * $qty, 2, '.', ''));
                            $items->item[$i]->addAttribute('tax', number_format($qty * ($mItem['products_price'] / (100 + $mItem['products_tax']) * $mItem['products_tax']), 2, '.', ''));
                        } else {
                            if ($mItem['article_name'] == 'pi-Merchant-Voucher') {
                                $items->addChild('item', PI_RATEPAY_VOUCHER);
                                $items->item[$i]->addAttribute('article-number', $mItem['article_number']);
                                $items->item[$i]->addAttribute('quantity', $qty);
                                $items->item[$i]->addAttribute('unit-price', number_format($mItem['article_netUnitPrice'], 2, '.', ''));
                                $items->item[$i]->addAttribute('total-price', number_format($qty * $mItem['article_netUnitPrice'], 2, '.', ''));
                                $items->item[$i]->addAttribute('tax', number_format(0, 2, '.', ''));
                            } elseif ($mItem['article_number'] == 'SHIPPING') {
                                $shippingCost = $mItem['article_netUnitPrice'];
                                $items->addChild('item', utf8_encode($mItem['article_name']));
                                $items->item[$i]->addAttribute('article-number', $mItem['article_number']);
                                $items->item[$i]->addAttribute('quantity', $qty);
                                $items->item[$i]->addAttribute('unit-price', number_format($shippingCost, 2, '.', ''));
                                $items->item[$i]->addAttribute('total-price', number_format($qty * $shippingCost, 2, '.', ''));
                                $items->item[$i]->addAttribute('tax', number_format(getShippingTaxAmount($qty * $shippingCost), 2, '.', ''));
                            } elseif ($mItem['article_number'] == 'DISCOUNT') {
                                $items->addChild('item', utf8_encode($mItem['article_name']));
                                $items->item[$i]->addAttribute('article-number', $mItem['article_number']);
                                $items->item[$i]->addAttribute('quantity', $qty);
                                $items->item[$i]->addAttribute('unit-price', number_format($mItem['article_netUnitPrice'], 2, '.', ''));
                                $items->item[$i]->addAttribute('total-price', number_format($qty * $mItem['article_netUnitPrice'], 2, '.', ''));
                                $items->item[$i]->addAttribute('tax', number_format(0, 2, '.', ''));
                            } elseif ($mItem['article_number'] == 'COUPON') {
                                $couponTax = ($mItem['article_netUnitPrice'] / (100 + $cab->getCouponTaxRate()) * 100 - $mItem['article_netUnitPrice']) * -1;
                                $items->addChild('item', utf8_encode($mItem['article_name']));
                                $items->item[$i]->addAttribute('article-number', $mItem['article_number']);
                                $items->item[$i]->addAttribute('quantity', $qty);
                                $items->item[$i]->addAttribute('unit-price', number_format($cab->getCouponAmount($mItem['article_netUnitPrice'] * -1), 2, '.', ''));
                                $items->item[$i]->addAttribute('total-price', number_format($qty * $cab->getCouponAmount($mItem['article_netUnitPrice'] * -1), 2, '.', ''));
                                $items->item[$i]->addAttribute('tax', number_format($cab->getCouponTaxAmount($mItem['article_netUnitPrice'] * -1), 2, '.', ''));
                            }
                        }
                        $i++;
                    }
                    $sql = "SELECT count( * ) as nr FROM " . $pi_table_prefix . "_orderdetails WHERE article_name = 'pi-Merchant-Voucher'";
                    $query = xtc_db_query($sql);
                    $nr = xtc_db_fetch_array($query);
                    if (!empty($_POST['voucherAmount']) && !empty($_POST['voucherAmountKomma'])) {
                        $items->addChild('item', PI_RATEPAY_VOUCHER);
                        $items->item[$i]->addAttribute('article-number', "pi-Merchant-Voucher-" . $nr['nr']);
                        $items->item[$i]->addAttribute('quantity', '1');
                        $items->item[$i]->addAttribute('unit-price', number_format($piRatepayVoucher, 2, ".", ""));
                        $items->item[$i]->addAttribute('total-price', number_format($piRatepayVoucher, 2, ".", ""));
                        $items->item[$i]->addAttribute('tax', number_format(0, 2, ".", ""));
                    }
                    $content->addChild('payment');
                    $payment = $content->payment;
                    $payment->addAttribute('method', $pi_payment_type);
                    $payment->addAttribute('currency', 'EUR');
                    $total = $order['value'] + $piRatepayVoucher;
                    // Add the shopping basket amoutn later because we need the shipping cost
                    $shoppingBasket->addAttribute('amount', number_format($total, 2, '.', ''));
                    $payment->addChild('amount', number_format($total, 2, '.', ''));
                    $payment->addChild('usage', utf8_encode($pi_ratepay->testOrLiveUsage()));
                    if ($pi_payment_type == "INSTALLMENT") {
                        $payment->addChild('installment-details');
                        $payment->addChild('debit-pay-type', 'BANK-TRANSFER');
                    }
                    $response = $ratepay->paymentOperation($request);
                    $first_name = removeSpecialChars(utf8_encode($order['customers_firstname']));
                    $last_name = removeSpecialChars(utf8_encode($order['customers_lastname']));
                    if ($response) {
                        $resultCode = (string) $response->head->processing->result->attributes()->code;
                        $result = (string) $response->head->processing->result;
                        $pi_ratepay->piRatepayLog($oID, $transactionArray['transaction_id'], $operation, $subOperation, $request, $response, $first_name, $last_name);
                        if ((string) $response->head->processing->status->attributes()->code == "OK" && (string) $response->head->processing->result->attributes()->code == "403") {
                            $sql = "INSERT INTO " . $pi_table_prefix . "_orderdetails\n\t\t\t\t\t\t\t\t\t\t(order_number, article_number,\n\t\t\t\t\t\t\t\t\t\tarticle_name, ordered, article_netUnitPrice) VALUES\n\t\t\t\t\t\t\t\t\t\t('" . $oID . "', 'pi-Merchant-Voucher-" . xtc_db_input($nr['nr']) . "',\n\t\t\t\t\t\t\t\t\t\t'pi-Merchant-Voucher',1," . xtc_db_input($piRatepayVoucher) . ")";
                            xtc_db_query($sql);
                            $sql = "INSERT INTO " . $pi_table_prefix . "_history\n\t\t\t\t\t\t\t\t\t\t(order_number, article_number,\n\t\t\t\t\t\t\t\t\t\tquantity, method, submethod) VALUES\n\t\t\t\t\t\t\t\t\t\t('" . xtc_db_input($oID) . "', 'pi-Merchant-Voucher-" . xtc_db_input($nr['nr']) . "',\n\t\t\t\t\t\t\t\t\t\t'1',\n\t\t\t\t\t\t\t\t\t\t'Credit created', 'added')";
                            xtc_db_query($sql);
                            $discountSql = "SELECT * FROM `orders_total` WHERE class='pi_ratepay_voucher' and orders_id = '" . xtc_db_input($oID) . "'";
                            $discountResult = xtc_db_query($discountSql);
                            $discountCount = xtc_db_num_rows($discountResult);
                            if ($discountCount > 0) {
                                $discountArray = xtc_db_fetch_array($discountResult);
                                $value = $discountArray['value'];
                                $value = $value + $piRatepayVoucher;
                                $value = number_format($value, 4, ".", "");
                                $discountTotalUpdate = "update orders_total set value = " . xtc_db_input($value) . " where class='pi_ratepay_voucher' and orders_id = '" . xtc_db_input($oID) . "'";
                                xtc_db_query($discountTotalUpdate);
                                $value = number_format($value, 2, ",", "");
                                $discountTotalUpdate = "update orders_total set text = '<font color=\"ff0000\">" . xtc_db_input($value) . " EUR</font>' where class='pi_ratepay_voucher' and orders_id = '" . xtc_db_input($oID) . "'";
                                xtc_db_query($discountTotalUpdate);
                            } else {
                                $value = number_format($piRatepayVoucher, 4, ".", "");
                                $valueFormat = number_format($value, 2, ",", "");
                                $discountTotalInsert = "INSERT INTO `orders_total` (`orders_id`, `title`, `text`, `value`, `class`, `sort_order`) VALUES ('" . xtc_db_input($oID) . "', 'Gutschein:', '<font color=\"ff0000\"> " . xtc_db_input($valueFormat) . " EUR</font>', " . xtc_db_input($value) . ", 'pi_ratepay_voucher', 98)";
                                xtc_db_query($discountTotalInsert);
                            }
                            $sql = "update orders_total set value = value+{$piRatepayVoucher} where class = 'ot_total' and orders_id = '" . xtc_db_input($oID) . "'";
                            xtc_db_query($sql);
                            $sql = "select value from orders_total where class = 'ot_total' and orders_id = '" . xtc_db_input($oID) . "'";
                            $totalq = xtc_db_query($sql);
                            $total = xtc_db_fetch_array($totalq);
                            $totalText = number_format($total['value'], 2, ",", ".");
                            $sql = "update orders_total set text = '<b>" . xtc_db_input($totalText) . " EUR</b>' where class = 'ot_total' and orders_id = '" . xtc_db_input($oID) . "'";
                            xtc_db_query($sql);
                            $message = PI_RATEPAY_SUCCESSVOUCHER;
                            return array('result' => 'SUCCESS', 'message' => $message);
                        } else {
                            $message = PI_RATEPAY_ERRORVOUCHER;
                            return array('result' => 'ERROR', 'message' => $message);
                        }
                    } else {
                        $message = PI_RATEPAY_SERVICE;
                        return array('result' => 'ERROR', 'message' => $message);
                    }
                }
            } else {
                $message = PI_RATEPAY_ERRORVOUCHER;
                return array('result' => 'ERROR', 'message' => $message);
            }
        }
    }
}
 public function isLive()
 {
     $pi_ratepay = new pi_ratepay_rate();
     $ratepay->live = $pi_ratepay->testOrLive();
     return $ratepay->live;
 }