<?php
use Stripe\Charge;
use Stripe\Error\Card;
use Stripe\Error\InvalidRequest;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
require_once $path . '/shop/checkout/stripe/stripe.config.php';

//Redirect to homepage if order id or stripe token is not defined
if (empty($_POST['order_id']) || empty($_POST['stripeToken'])) {
    header("Location: " . SITE_URL);
    exit();
}

ob_start();

try {
    $newbasket = new Order($_POST['order_id']);
    $order_ref = config('site.tnx_prefix') . $newbasket->getId();
    $total_amount = $newbasket->getTotalCost();

    //Add order ref for submiting to stripe
    $metadata = [
        'Order Reference' => $order_ref
    ];

    //Add coupon information for submiting to stripe
    if ($newbasket->coupon_code !== null) {
        $metadata['Coupon code'] = $newbasket->coupon_code;
    }

    //Charge order
    $charge = Charge::create(array(
      'source'   => $_POST['stripeToken'],
      'amount'   => round($total_amount * 100),  //the amount in pennies
      'currency' => "GBP",
      'metadata' => $metadata
    ));

    //Mark order as paid and save stripe charge information
    $newbasket->markPaid();
    $newbasket->saveStripe([
        'charge_id' => $charge->id,
        'order_ref' => $order_ref,
        'amount' => $total_amount
    ]);

    $newbasket->sendOrderConfirmation();

    $_SESSION['order_id'] = $newbasket->getId();
    $_SESSION['basket_id'] = '';

    if (defined('PPC_TRACKING') && PPC_TRACKING === true) {
        track('sale', $newbasket->getTotalCost(), $newbasket->ref, $newbasket->keywords);
    }

    if (defined('GOOGLE_ANALYTICS_USERAGENT') && GOOGLE_ANALYTICS_USERAGENT != '') {
        $tracking_code[] = $GLOBALS['twig']->render('analytics_js.twig', [
            'order'    => $newbasket,
            'settings' => $GLOBALS['settings'],
        ]);
    }

    $order_failed = false;
} catch (Card $e) {
    //i.e. the card has been declined
    $order_failed = true;
} catch (InvalidRequest $e) {
    //i.e. payment token was already used
    $order_failed = true;
}

$page_html = ob_get_clean();

//Renders template regarding on order outcome
if ($order_failed === true) {

    $page_meta = [
        'title' => 'Your order has not been processed | ' . config('app.name'),
        'page_title' => 'Order issue',
        'page_sub_title' => 'Your order has not been processed',
    ];

    echo $twig->render('shop/checkout/order_failed.twig', [
        'page_meta' => $page_meta,
        'page_html' => $page_html,
    ]);

} else {

    $page_meta = [
        'title' => 'Your order is now complete | ' . config('app.name'),
        'page_title' => 'Order Complete',
        'page_sub_title' => 'Thank you for shopping online with ' . config('app.name'),
    ];

    echo $twig->render('shop/checkout/order_complete.twig', [
        'page_meta' => $page_meta,
        'page_html' => $page_html,
        'basket_object' => $newbasket,
        'tracking_code' => $tracking_code
    ]);

}
