<?php
session_start();
include 'db.php';

$id = (int)$_POST['id'];
$qty = (int)$_POST['qty'];

if(isset($_SESSION['cart'][$id])){
    $_SESSION['cart'][$id] = $qty;
}

// Calculate new subtotal
$product = $conn->query("SELECT * FROM products WHERE id=$id")->fetch_assoc();
$price = $product['sale_price'] ?: $product['price'];
$subtotal = $price * $qty;

// Calculate total
$total = 0;
foreach($_SESSION['cart'] as $pid => $pq){
    $p = $conn->query("SELECT * FROM products WHERE id=$pid")->fetch_assoc();
    $pPrice = $p['sale_price'] ?: $p['price'];
    $total += $pPrice * $pq;
}

// Return JSON
echo json_encode([
    "subtotal" => number_format($subtotal,2),
    "total" => number_format($total,2)
]);
?>