<?php
require_once '../includes/config.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isUserLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Silakan login terlebih dahulu']);
    exit;
}

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get product ID and quantity
$product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;

// Validate product ID and quantity
if ($product_id <= 0 || $quantity <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid product ID or quantity']);
    exit;
}

try {
    // Check if product exists and has stock
    $conn = connectDB();
    $stmt = $conn->prepare("SELECT * FROM products WHERE product_id = :product_id");
    $stmt->bindParam(':product_id', $product_id);
    $stmt->execute();
    
    if ($product = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // Check if product has enough stock
        if ($product['stock'] <= 0) {
            echo json_encode(['success' => false, 'message' => 'Produk tidak tersedia']);
            exit;
        }
        
        // Initialize cart if not exists
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = array();
        }
        
        // Check if product already in cart
        if (isset($_SESSION['cart'][$product_id])) {
            // Calculate new quantity
            $newQuantity = $_SESSION['cart'][$product_id] + $quantity;
            
            // Check if new quantity exceeds stock
            if ($newQuantity > $product['stock']) {
                if ($_SESSION['cart'][$product_id] == $product['stock']) {
                    // User already has maximum available stock in cart
                    echo json_encode([
                        'success' => false,
                        'message' => 'Stok sudah mencapai maximum'
                    ]);
                    exit;
                } else {
                    // Adjust to maximum available stock
                    $newQuantity = $product['stock'];
                    $_SESSION['cart'][$product_id] = $newQuantity;
                    
                    // Calculate cart count
                    $cartCount = 0;
                    foreach($_SESSION['cart'] as $qty) {
                        $cartCount += $qty;
                    }
                    
                    echo json_encode([
                        'success' => true,
                        'message' => 'Stok produk disesuaikan dengan yang tersedia',
                        'cartCount' => $cartCount
                    ]);
                    exit;
                }
            }
            
            $_SESSION['cart'][$product_id] = $newQuantity;
        } else {
            // Add new product to cart
            // Check if requested quantity exceeds stock
            if ($quantity > $product['stock']) {
                // Adjust to maximum available stock
                $quantity = $product['stock'];
                $_SESSION['cart'][$product_id] = $quantity;
                
                // Calculate cart count
                $cartCount = 0;
                foreach($_SESSION['cart'] as $qty) {
                    $cartCount += $qty;
                }
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Stok produk disesuaikan dengan yang tersedia',
                    'cartCount' => $cartCount
                ]);
                exit;
            } else {
                $_SESSION['cart'][$product_id] = $quantity;
            }
        }
        
        // Calculate cart count
        $cartCount = 0;
        foreach($_SESSION['cart'] as $qty) {
            $cartCount += $qty;
        }
        
        // Set success message with cart count
        echo json_encode([
            'success' => true, 
            'message' => 'Produk berhasil ditambahkan ke keranjang',
            'cartCount' => $cartCount
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Produk tidak ditemukan']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Stok sudah mencapai maximum']);
}
?> 