<?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'] : 0;

// 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)) {
        // Initialize cart if not exists
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = array();
        }
        
        // Check if product in cart
        if (isset($_SESSION['cart'][$product_id])) {
            // Check if quantity exceeds stock
            if ($quantity > $product['stock']) {
                $quantity = $product['stock'];
                $_SESSION['cart'][$product_id] = $quantity;
                echo json_encode([
                    'success' => true,
                    'message' => 'Jumlah produk telah disesuaikan dengan stok yang tersedia',
                    'quantity' => $quantity
                ]);
                exit;
            }
            
            // Update quantity
            $_SESSION['cart'][$product_id] = $quantity;
            
            // Calculate new total
            $totalAmount = 0;
            foreach ($_SESSION['cart'] as $id => $qty) {
                $stmt = $conn->prepare("SELECT price FROM products WHERE product_id = :id");
                $stmt->bindParam(':id', $id);
                $stmt->execute();
                $productPrice = $stmt->fetch(PDO::FETCH_ASSOC);
                $totalAmount += $qty * $productPrice['price'];
            }
            
            echo json_encode([
                'success' => true, 
                'message' => 'Keranjang berhasil diperbarui',
                'total' => $totalAmount,
                'subtotal' => $quantity * $product['price']
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Produk tidak ada dalam keranjang']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Produk tidak ditemukan']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan: ' . $e->getMessage()]);
}
?> 