<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

require_once __DIR__ . "/required.php";
require_once __DIR__ . "/lib/item.php";

switch ($VARS['action']) {
    case "addtocart":
        $item = $VARS['item'];
        $qty = $VARS['qty'];

        if (!$binstack->has('items', ['AND' => ['itemid' => $item, 'price[>]' => 0]])) {
            header('Location: ./?page=cart&msg=invaliditem');
            die("Invalid item");
        }
        $cart = [];

        if (!empty($_SESSION['cart'])) {
            $cart = $_SESSION['cart'];
        }

        if (empty($cart[$item])) {
            $cart[$item] = $qty;
        } else {
            $cart[$item] += $qty;
        }

        $_SESSION['cart'] = $cart;

        header('Location: ./?page=cart&msg=itemadded');
        die();

        break;
    case "updatecart":
        $item = $VARS['item'];
        $qty = $VARS['qty'];

        $cart = [];

        if (!empty($_SESSION['cart'])) {
            $cart = $_SESSION['cart'];
        }

        $cart[$item] = $qty;

        if ($qty <= 0) {
            unset($cart[$item]);
        }

        $_SESSION['cart'] = $cart;

        header('Location: ./?page=cart&msg=itemupdated');

        break;
}