<?php
session_start();
include_once 'database/shikanisha.kts.php'; // Include your database connection file

if (isset($_POST['add'])) {
    $id    = $_POST['id'];
    $name  = $_POST['name'];
    $qty   = $_POST['qty'];
    if ($_POST['price'] === 'custom') {
        $price = $_POST['custom_price'];
    } else {
        $price = $_POST['price'];
    }

    // Check if store qty is available before adding to shopz
    $query_check = "SELECT shop_quantity FROM products WHERE product_id = ?";
    $stmt_check = mysqli_prepare($conn, $query_check);

    if ($stmt_check) {
        mysqli_stmt_bind_param($stmt_check, "i", $id);
        mysqli_stmt_execute($stmt_check);

        mysqli_stmt_bind_result($stmt_check, $store_quantity);
        mysqli_stmt_fetch($stmt_check);

        if ($store_quantity < $qty) {
            // Product is unavailable
            echo "Product the quantity requested is unavailable.";
            exit();
        }

        // Product is available, add to shopz
        $session_array = array(
            'id'    =>  $id,
            'name'  =>  $name,
            'price' =>  $price,
            'qty'   =>  $qty
        );

        if (!empty($_SESSION['shopz'])) {
            $session_array_id = array_column($_SESSION['shopz'], 'id');
            if (in_array($id, $session_array_id)) {
                foreach ($_SESSION['shopz'] as $key => $val) {
                    if ($_SESSION['shopz'][$key]['id'] === $id) {
                        if (!empty($qty)) {
                            $_SESSION['shopz'][$key]['qty'] = $_SESSION['shopz'][$key]['qty'] + $qty;
                        }
                    }
                }
            } else {
                if (!empty($qty)) {
                    $_SESSION['shopz'][] = $session_array;
                }
            }
        } else {
            if (!empty($qty)) {
                $_SESSION['shopz'][] = $session_array;
            }
        }
        
        echo "Product added to the cart successfully"; // Success message
    } else {
        echo "Error: " . mysqli_error($conn); // Error message
    }
} else {
    echo "Invalid request";
}
?>
