<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

$itemId = (int)($_POST['item_id'] ?? 0);
$qty = (float)($_POST['qty'] ?? 1);

if ($itemId <= 0) {
    exit('Invalid item');
}

if ($qty <= 0) {
    $qty = 1;
}

/*
    Load item
*/
$stmt = $db->prepare("
    SELECT *
    FROM items
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$itemId]);

$item = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$item) {
    exit('Item not found');
}

/*
    Init cart
*/
if (!isset($_SESSION['pos_cart'])) {
    $_SESSION['pos_cart'] = [];
}

/*
    GST %
    assuming item.gst exists
*/
$gstPercent = (float)($item['gst'] ?? 0);
$price = (float)$item['price'];

if (isset($_SESSION['pos_cart'][$itemId])) {

    /*
        Increase existing qty
    */
    $_SESSION['pos_cart'][$itemId]['qty'] += $qty;

} else {

    /*
        Add new
    */
    $_SESSION['pos_cart'][$itemId] = [
        'item_id' => $item['id'],
        'name'    => $item['name'],
        'price'   => $price,
        'gst'     => $gstPercent,
        'qty'     => $qty
    ];
}

echo 'OK';
?>