<?php

require_once "config.php";
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        
        $ckodemember = $_GET["ckodemember"];
        
        $queryKeranjang = $conn->query("SELECT * FROM tbkeranjang WHERE ckodemember = '$ckodemember'");

        $items = [];
        $groupedItems = [];

        if ($queryKeranjang->num_rows > 0) {
            while ($row = $queryKeranjang->fetch_assoc()) {
                $ckodebrg = $row['cKodeBrg'];
                $nQty = (float) $row['nQty'];

                if (isset($groupedItems[$ckodebrg])) {
                    $groupedItems[$ckodebrg]['nQty'] += $nQty;
                } else {
                    $groupedItems[$ckodebrg] = $row;
                    $groupedItems[$ckodebrg]['nQty'] = $nQty;
                }
            }

            foreach ($groupedItems as $ckodebrg => $item) {
                $nQty = (float) $item['nQty'];
                
                $queryStock = $conn->query("SELECT nQtyStock FROM vwstock WHERE ckodebrg = '$ckodebrg'");
                
                $stock = 0;
                if ($queryStock->num_rows > 0) {
                    $stockResult = $queryStock->fetch_assoc();
                    $stock = (float) $stockResult['nQtyStock'];
                }

                $item['nQtyStock'] = $stock;

                if ($nQty > $stock) {
                    $item['stockStatus'] = 'Insufficient stock';
                } else {
                    
                    $item['stockStatus'] = 'Sufficient stock';
                    // echo json_encode([]);
                    // exit; 
                }

                $items[] = $item;
            }

            echo json_encode($items);
        } else {
            echo json_encode([]);
        }

        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}

mysqli_close($conn);

?>
