<?php
require('config.php');

// Check if the necessary POST data is present
if (isset($_POST['stockData'])) {
    $stockData = $_POST['stockData'];

    // Decode the JSON data
    $stocksArray = json_decode($stockData, true);

    foreach ($stocksArray as $row) {
        // Check if the productID and size already exist in the store_stock table
        $checkStmt = $connect->prepare("SELECT COUNT(*) FROM store_stock WHERE productID = ? AND size = ?");
        $checkStmt->bind_param("is", $row["productID"], $row["size"]);
        $checkStmt->execute();
        $checkStmt->bind_result($count);
        $checkStmt->fetch();
        $checkStmt->close();

        if ($count > 0) {
            // If the product exists, skip the insertion
            $response['error'] = true;
            $response['message'] = "Product with ID " . $row["productID"] . " and size " . $row["size"] . " already exists in stock! Add more product stock from the edit section.";
            echo json_encode($response);
            exit;
        } else {
            // Prepare the SQL statement using parameterized queries to prevent SQL injection
            $stmt = $connect->prepare("INSERT INTO store_stock (productID, quantity, productPrice, store_price, size, addedBy, dateAdded) VALUES (?, ?, ?, ?, ?, ?, ?)");

            // Bind parameters to the SQL statement
            $stmt->bind_param(
                "iiiisis",
                $row["productID"],
                $row["quantity"],
                $row["productPrice"],
                $row["store_price"],
                $row["size"],
                $row["addedBy"],
                $row["dateAdded"]
            );

            // Execute the prepared statement
            $stmt->execute();
            $stmt->close();
        }
    }

    $response['error'] = false;
    $response['message'] = "Stock added successfully";
} else {
    $response['error'] = true;
    $response['message'] = "Insufficient parameters, please provide stock data.";
}

// Output the response as JSON
echo json_encode($response);
?>
