<?php
session_start();

// Database connection
require_once 'shikanisha.kts.php';

// Check if the cart exists in the session; if not, create an empty cart
if (!isset($_SESSION['cartz'])) {
    $_SESSION['cartz'] = [];
}

// Handle adding or updating items in the cart
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'updateCartItem') {
        $productId = $_POST['product_id'];
        
        // Check if 'quantity' and 'price' indexes are set in the POST data
        $quantity = isset($_POST['quantity']) ? $_POST['quantity'] : 0;
        $price = isset($_POST['price']) ? $_POST['price'] : 0;

        // Update the quantity for the specific item in the cart
        foreach ($_SESSION['cartz'] as &$cartItem) {
            if ($cartItem['product_id'] === $productId) {
                $cartItem['quantity'] = $quantity;
                $cartItem['price'] = $price;
                break;
            }
        }

        header('Content-Type: application/json');
        $response = ['success' => true, 'message' => 'Item updated in cart'];
        echo json_encode($response);
        exit;
    } elseif ($_POST['action'] === 'addToCart') {
        $item = [
            'product_id' => $_POST['product_id'],
            'item_name' => $_POST['item_name'],
            'price' => $_POST['price'],
            'quantity' => $_POST['quantity']
        ];

        // Check if the price is custom, and if yes, use custom price
        if ($_POST['price'] === 'custom') {
            $customPrice = isset($_POST['custom_price']) ? $_POST['custom_price'] : null;

            if ($customPrice !== null && is_numeric($customPrice) && $customPrice > 0) {
                $item['price'] = $customPrice;
            } else {
                // Handle the case where the custom price is invalid
                header('Content-Type: application/json');
                $response = ['message' => 'Invalid custom price'];
                echo json_encode($response);
                exit;
            }
        }

        // Check the available quantity in the inventory
        $productId = $item['product_id'];
        $requestedQuantity = intval($item['quantity']);

        $sqlCheckQuantity = "SELECT shop_quantity AS available_quantity
                             FROM products
                             WHERE product_id = '$productId'";
        $result = mysqli_query($conn, $sqlCheckQuantity);

        if ($result && mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $availableQuantity = intval($row['available_quantity']);

            if ($availableQuantity >= $requestedQuantity) {
                // Quantity is available, check if the item exists in the cart
                $itemExists = false;

                foreach ($_SESSION['cartz'] as &$cartItem) {
                    if ($cartItem['product_id'] === $productId) {
                        // Item with the same product ID exists; increase quantity
                        $cartItem['quantity'] += $requestedQuantity;
                        $itemExists = true;
                        break;
                    }
                }

                if (!$itemExists) {
                    // Item does not exist in the cart; add it
                    $_SESSION['cartz'][] = $item;
                }

                header('Content-Type: application/json');
                $response = ['message' => 'Item added to cart'];
                echo json_encode($response);
                exit;
            } else {
                // Insufficient quantity
                header('Content-Type: application/json');
                $response = ['message' => 'Requested Quantity is not available'];
                echo json_encode($response);
                exit;
            }
        } else {
            // Query error or item not found in inventory
            header('Content-Type: application/json');
            $response = ['message' => 'An error occurred while checking the quantity'];
            echo json_encode($response);
            exit;
        }
    }
}
?>
