<?php
header('Content-Type: application/json');
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/config/db.php';

$response = ['status' => 'error', 'message' => 'Invalid request.'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'add' && isset($_POST['product_id'])) {
        $product_id = intval($_POST['product_id']);
        $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
        $size = isset($_POST['size']) ? trim($_POST['size']) : 'M';
        $color = isset($_POST['color']) ? trim($_POST['color']) : 'Midnight Black';
        
        if ($quantity <= 0) {
            $quantity = 1;
        }
        
        // Check if product exists and is in stock
        $stmt = $pdo->prepare("SELECT name, stock FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch();
        
        if ($product) {
            if (!isset($_SESSION['cart'])) {
                $_SESSION['cart'] = [];
            }
            if (!isset($_SESSION['cart_details'])) {
                $_SESSION['cart_details'] = [];
            }
            
            // Check current cart qty vs stock
            $current_in_cart = isset($_SESSION['cart'][$product_id]) ? $_SESSION['cart'][$product_id] : 0;
            $new_qty = $current_in_cart + $quantity;
            
            // Set session cart and details
            $_SESSION['cart'][$product_id] = $new_qty;
            $_SESSION['cart_details'][$product_id] = [
                'size' => $size,
                'color' => $color
            ];
            
            // Calculate total unique items or total qty in cart
            $cart_count = 0;
            foreach ($_SESSION['cart'] as $pid => $qty) {
                $cart_count += $qty;
            }
            
            $response = [
                'status' => 'success',
                'product_name' => $product['name'],
                'cart_count' => $cart_count,
                'message' => 'Product added successfully.'
            ];
        } else {
            $response = ['status' => 'error', 'message' => 'Product not found.'];
        }
    }
}

echo json_encode($response);
exit;
?>
