<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    exit('Unauthorized');
}

include_once "../config/database.php";

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    exit('Invalid Product');
}

$product_id = (int)$_GET['id'];

$sql = "SELECT
            id,
            product_name,
            selling_price,
            stock
        FROM products
        WHERE id = {$product_id}
        AND status = 1
        LIMIT 1";

$result = mysqli_query($conn, $sql);

if (!$result || mysqli_num_rows($result) == 0) {
    exit('Product Not Found');
}

$product = mysqli_fetch_assoc($result);

$currentQty = 0;

if (isset($_SESSION['cart'][$product_id])) {
    $currentQty = (int)$_SESSION['cart'][$product_id]['qty'];
}

$newQty = $currentQty + 1;

if ($newQty > (int)$product['stock']) {
    exit('Stock Not Available');
}

$_SESSION['cart'][$product_id] = [

    'id'    => (int)$product['id'],

    'name'  => $product['product_name'],

    'price' => (float)$product['selling_price'],

    'qty'   => $newQty

];

echo "success";
?>