<?php
session_start();
include(__DIR__ . '/../config.php');

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

/* ADD TO CART WITH STOCK CHECK */
if(isset($_POST['product_id'])){

    $id = $_POST['product_id'];
    $qty = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;

    // Get product stock
    $stmt = $pdo->prepare("SELECT stock FROM products WHERE id=?");
    $stmt->execute([$id]);
    $product = $stmt->fetch();

    if(!$product){
        $_SESSION['error'] = "Product not found!";
        header("Location: products.php");
        exit();
    }

    $stock = $product['stock'];

    // Already in cart
    $currentQty = $_SESSION['cart'][$id] ?? 0;
    $newQty = $currentQty + $qty;

    if($stock <= 0){
        $_SESSION['error'] = "Item is not available!";
    }
    elseif($newQty > $stock){
        $_SESSION['error'] = "Only $stock item(s) available!";
    }
    else{
        $_SESSION['cart'][$id] = $newQty;
        $_SESSION['success'] = "Item added to cart!";
    }
}

/* REMOVE ITEM */
if(isset($_GET['remove'])){
    $id = $_GET['remove'];
    unset($_SESSION['cart'][$id]);
}

/* UPDATE QUANTITY */
if(isset($_POST['update'])){
    foreach($_POST['qty'] as $id => $qty){

        $stmt = $pdo->prepare("SELECT stock FROM products WHERE id=?");
        $stmt->execute([$id]);
        $product = $stmt->fetch();

        if($qty <= 0){
            unset($_SESSION['cart'][$id]);
        }
        elseif($qty > $product['stock']){
            $_SESSION['error'] = "Stock limit exceeded!";
        }
        else{
            $_SESSION['cart'][$id] = $qty;
        }
    }
}

header("Location: checkout.php");
exit();