<?php
require 'includes/auth.php';
require_login();
require 'includes/db.php';


$pid = intval($_POST['product_id'] ?? 0);
$qty = max(1, intval($_POST['qty'] ?? 1));


if (!$pid) { header('Location: sales_pos.php'); exit; }
$stmt = $mysqli->prepare('SELECT id, name, selling_price, quantity FROM products WHERE id = ? LIMIT 1');
$stmt->bind_param('i', $pid);
$stmt->execute();
$p = $stmt->get_result()->fetch_assoc();
if (!$p) { header('Location: sales_pos.php'); exit; }


if (!isset($_SESSION['cart'])) $_SESSION['cart'] = [];
// if exists, increment
$found = false;
foreach($_SESSION['cart'] as &$it){
if ($it['id'] == $p['id']){ $it['qty'] += $qty; $found = true; break; }
}
if (!$found){
$_SESSION['cart'][] = [
'id' => $p['id'],
'name' => $p['name'],
'price' => (float)$p['selling_price'],
'qty' => $qty
];
}
header('Location: sales_pos.php');