<?php
require './vendor/autoload.php';

use League\Plates\Engine;

class User
{
    public array $cart;
    public int $wallet;

    public function __construct($wallet, $cart = [])
    {
        $this->wallet = $wallet;
        $this->cart = $cart;
    }
}

$user = isset($_GET['user']) && !empty($_GET['user']) ? $_GET['user'] : false;

if(!$user) {
    show_source(__FILE__);
    exit;
}

$shop = [
    'products' => [
        'h2hc_ticket' => 500,
        'hackingclub' => 4000,
        'flipper' => 4000,
        'rubberducky' => 500,
        'mullvad' => 100,
        'njalla' => 200
    ]
];

try {
    $user = unserialize(base64_decode($user));

    $i = 0;
    
    foreach($user->cart as $product) {
        if(in_array($product, array_keys($shop['products']))) {
            $product_value = $shop['products'][$product];

            if($user->wallet < $product_value) {
                continue;
            }

            $i++;
        }
    }

    $templates = new Engine(dirname(__FILE__) . '/templates', 'php');
    
    if(!$i) {
        $status = 'error';
        $message = 'Purchase failed';
    } else {
        $status = 'success';
        $message = 'Purchase successful';
    }
    
    echo $templates->render('purchase', ['message' => $message, 'status' => $status]);

} catch(Exception $e) {
    die('Invalid user data');
}