<?php
include 'config.php';

if(isset($_POST['idcart']) && isset($_POST['idproduk']) && isset($_POST['new_quantity'])) {
    $idcart = (int)$_POST['idcart'];
    $idproduk = (int)$_POST['idproduk'];
    $new_quantity = (int)$_POST['new_quantity'];
    
    // Get current product info to check stock
    $cekBarang = mysqli_query($conn, "SELECT * FROM produk WHERE idproduk='$idproduk'");
    $stocknya = mysqli_fetch_array($cekBarang);
    $current_stock = $stocknya['stock'];
    
    // Get current cart quantity to calculate stock adjustment
    $cart_item = mysqli_query($conn, "SELECT quantity FROM keranjang WHERE idcart='$idcart'");
    $current_cart = mysqli_fetch_assoc($cart_item);
    $current_qty = $current_cart['quantity'];
    
    // Calculate the difference
    $qty_diff = $new_quantity - $current_qty;
    
    // Check if new quantity is valid
    if($qty_diff > $current_stock) {
        echo json_encode([
            'success' => false,
            'message' => 'Jumlah melebihi stok yang tersedia!'
        ]);
    } else {
        // Update cart quantity
        $update_cart = mysqli_query($conn, "UPDATE keranjang SET quantity='$new_quantity' WHERE idcart='$idcart'");
        
        if($update_cart) {
            // Update product stock
            $new_stock = $current_stock - $qty_diff;
            $update_stock = mysqli_query($conn, "UPDATE produk SET stock='$new_stock' WHERE idproduk='$idproduk'");
            
            if($update_stock) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Jumlah berhasil diperbarui'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Gagal memperbarui stok produk'
                ]);
            }
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Gagal memperbarui jumlah di keranjang'
            ]);
        }
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Data tidak lengkap'
    ]);
}
?>