<?php

use Mtc\Shop\Order\Protx;

$path = "../../../";
require_once $path . 'core/includes/header.inc.php';
$basket = new Basket();
$basket->Go_Basket();

$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'),
];

//Allows get variable for order_id to be set so the page can be tested without having to complete the checkout each time
$test_page = false;

if ((empty($_POST['is_phone']) || empty($_POST['transaction_id'])) && !$test_page) {
    header('Location: /shop/checkout/basket_overview.php?error=no_tx');
    exit();
}

if (empty($_SESSION['phone_order_id']) && !$test_page) {
    $values = array();
    $values['VendorTxCode'] = "PHONE-" . $_REQUEST['transaction_id'];

    $paymentExists = Protx::query()
        ->where('VendorTxCode', $values['VendorTxCode'])
        ->exists();

    if (!$paymentExists) {

        $values['Amount'] = $basket->cost_total;

        $newbasket = Order::getFromBasketId($_SESSION['basket_id']);
        $newbasket->markPaid();
        $newbasket->sendOrderConfirmation();

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

        $newbasket = new Order($_REQUEST['order_id']);
        $_SESSION['phone_order_id'] = $newbasket->getId();
        $_SESSION['basket_id'] = '';

    }
}

if (!empty($_REQUEST['order_id']) || $test_page) {
    $basket = new Order($_REQUEST['order_id']);
    echo $twig->render('shop/checkout/order_complete.twig', [
        'page_meta' => $page_meta,
        'basket_object' => $basket,
    ]);
} else {
    header('Location: /');
    exit;
}
