<?php
// actions/add_to_cart.php
session_start();
require_once('../config/db.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../sales.php');
    exit;
}

$productID = $_POST['ProductID'] ?? '';
$name = $_POST['Name'] ?? '';
$qty = max(1, (int)($_POST['Quantity'] ?? 1));
$price = number_format((float)($_POST['PricePerUnit'] ?? 0), 2, '.', '');

if (!$productID) {
    $_SESSION['error'] = 'Please select a product.';
    header('Location: ../sales.php');
    exit;
}

// fetch current stock to validate
$stmt = $pdo->prepare("SELECT StockQuantity FROM products WHERE ProductID = ?");
$stmt->execute([$productID]);
$row = $stmt->fetch();

$stock = $row ? (int)$row['StockQuantity'] : 0;
if ($qty > $stock) {
    $_SESSION['error'] = 'Requested quantity exceeds available stock.';
    header('Location: ../sales.php');
    exit;
}

// prepare cart item
$item = [
    'ProductID' => $productID,
    'Name' => $name,
    'Qty' => $qty,
    'Price' => $price,
    'Total' => number_format($qty * $price, 2, '.', '')
];

if (!isset($_SESSION['cart'])) $_SESSION['cart'] = [];

// merge if exists
$found = false;
foreach ($_SESSION['cart'] as &$c) {
    if ($c['ProductID'] === $productID) {
        $c['Qty'] += $qty;
        $c['Total'] = number_format($c['Qty'] * $c['Price'], 2, '.', '');
        $found = true;
        break;
    }
}
unset($c);

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

header('Location: ../cart.php');
exit;
