<?php

if (PAYPAL) {

    // Setup basic details depending on if this is a test
    if (PAYPAL_TEST) {
        $url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
        $email = PAYPAL_TEST_EMAIL;
        $paypal_cert_id = 'GFH9926S79742';
        $cert_prefix = 'dev_';
    } else {
        $url =  'https://www.paypal.com/cgi-bin/webscr';
        $email = PAYPAL_EMAIL;
        $paypal_cert_id = PAYPAL_CERT_ID;
        $cert_prefix = '';
    }

    // Get the location of the security keys/certificates
    $ssl_dir = __DIR__ . '/certificates/';
    $paypal_ours_cert = $ssl_dir . $cert_prefix . 'ours.crt';
    $paypal_ours_key  = $ssl_dir . $cert_prefix . 'ours.key';
    $paypal_gw_cert   = $ssl_dir . $cert_prefix . 'paypal.crt';

    // Get total cost excluding vat if enabled.
    if (VAT_ENABLED) {
        $totalcost = $newbasket->cost_total - $newbasket->cost_vat - $newbasket->cost_delivery;
    } else {
        $totalcost = $newbasket->cost_total - $newbasket->cost_delivery;
    }

    $invoiceBase = config('site.tnx_prefix') . $newbasket->order_id;

    try {
        $invoiceToken = bin2hex(random_bytes(4));
    } catch (Exception $exception) {
        $invoiceToken = substr(md5(microtime(true)), -8);
    }

    $paypalInvoice = $invoiceBase . '-' . $invoiceToken;

    $params = array(
        'cmd'              => '_xclick',
        'item_name'        => config('app.name') . ' Order',
        'business'         => $email,
        'invoice'          => $paypalInvoice,
        'amount'           => sprintf("%.2f", $totalcost),
        'tax'              => (VAT_ENABLED ? sprintf("%.2f", $newbasket->cost_vat) : ''),
        'shipping'         => sprintf("%.2f", $newbasket->cost_delivery),
        'currency_code'    => 'GBP',
        'lc'               => 'GB',
        'bn'               => 'PP-BuyNowBF',
        'address_override' => 0,
        'first_name'       => clean_page($newbasket->address['shipping']['firstname']),
        'last_name'        => clean_page($newbasket->address['shipping']['lastname']),
        'address1'         => clean_page($newbasket->address['shipping']['address1']),
        'city'             => clean_page($newbasket->address['shipping']['city']),
        'state'            => clean_page($newbasket->address['shipping']['state']),
        'zip'              => clean_page($newbasket->address['shipping']['postcode']),
        'country'          => clean_page($newbasket->address['shipping']['country']),
        'notify_url'       => SITE_URL . '/shop/checkout/paypal/order_paypal.php',
        'return'           => SITE_URL . '/shop/checkout/paypal/paypal_complete.php',
        'return_cancel'    => SITE_URL . '/shop/checkout/paypal/paypal_failed.php',
    );

    $_SESSION['order_id'] = $newbasket->order_id;
    $_SESSION['paypal_invoice'] = $paypalInvoice;
    $newbasket->order_ref = $paypalInvoice;
    \Mtc\Shop\Order::query()
        ->where('id', $newbasket->order_id)
        ->update(['order_ref' => $paypalInvoice]);

    //paypal requires non-empty state value for some countries
    if (empty($params['state'])) {
        $params['state'] = '-';
    }

    try {
        $paypal_button = PayPal_Button::make($paypal_ours_cert, $paypal_ours_key, $paypal_cert_id, $paypal_gw_cert);

        ?>
        <form id="protx_form" action="<?=$url?>" method="post" class="PayPalForm">
            <?=$paypal_button->getFormFields($params);?>
            <button type="submit" name="payment" class="paypalSubmit"><img src="/core/images/paypalPay.gif" alt="Pay with Paypal" /></button>
        </form>
        <?php

        if (PAYPAL_TEST) {
            ?>
            <div class="error">This site is currently processing orders through the Paypal Sandbox!</div>
            <?php
        }
    } catch (Exception $e) {
        if (DEV_MODE) {
            ?>
            <div class="error"><?=$e->getMessage()?></div>
            <?php
        }
    }

}
