<?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();

        Protx::query()->updateOrCreate(
            [
                'order_id' => $newbasket->getId(),
                'VendorTxCode' => $values['VendorTxCode'],
            ],
            [
                'VendorTxCode' => $values['VendorTxCode'],
                'VPSTxId' => '',
                'TxAuthNo' => '',
                'Amount' => $values['Amount'],
                'AVSCV2' => '',
                'AddressResult' => '',
                'PostCodeResult' => '',
                'CV2Result' => '',
                'GiftAid' => '',
                '3DSecureStatus' => 'PHONE',
                'CAVV' => '',
                'SecurityKey' => '',
                'released' => 1,
                'released_amount' => $values['Amount'],
                'AmountRemaining' => 0,
                'type' => 'phone',
            ]
        );

        $basketIdForCleanup = $newbasket->getBasketId();
        $paidOrderId = $newbasket->getId();

        $newbasket->sendOrderConfirmation();

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

        \Mtc\Shop\Order::query()
            ->where('basket_id', $basketIdForCleanup)
            ->where('id', '!=', $paidOrderId)
            ->get()
            ->each(function ($duplicate) {
                if ((int)($duplicate->paid ?? 0) === 0) {
                    \Mtc\Shop\Order::deleteById($duplicate->id);
                }
            });

        $_SESSION['phone_order_id'] = $newbasket->getId();
        $_SESSION['basket_id'] = '';
        unset($_SESSION['order_id']);
        unset($_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;
}
