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

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

    $productData = $_POST['productData'];

    // Decode the JSON data
    $productsArray = json_decode($productData, true);

    $response = []; // Initialize response array
    $allSuccess = true; // Track if all inserts are successful
    $errors = []; // Collect error messages

    foreach ($productsArray as $row) {
        // Check if 'productCode' is not null
        if (!isset($row['productCode']) || empty($row['productCode'])) {
            $allSuccess = false;
            $errors = "Product code is missing or null for one or more items.";
            continue;
        }

        // Prepare the SQL statement using parameterized queries to prevent SQL injection
        $stmt = $connect->prepare("INSERT INTO products (productPicture, productCategory, productName, productColor, productQuality, productDescription, date_added, added_by, productType, productCode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        if (!$stmt) {
            // Add a database preparation error
            $allSuccess = false;
            $errors[] = "Database preparation error: " . $connect->error;
            continue;
        }

        // Bind parameters to the SQL statement
        $stmt->bind_param(
            "sssssssiss",
            $row["productPicture"],
            $row["productCategory"],
            $row["productName"],
            $row["productColor"],
            $row["productQuality"],
            $row["productDescription"],
            $row["date_added"],
            $row["added_by"],
            $row["productType"],
            $row["productCode"]
        );

        // Execute the prepared statement
        if (!$stmt->execute()) {
            $allSuccess = false;
            $errors[] = "Database error: " . $stmt->error;
        }

        $stmt->close();
    }

    // Check if there were any errors
    if ($allSuccess) {
        $response['error'] = false;
        $response['message'] = "Product(s) added successfully.";
    } else {
        $response['error'] = true;
        $response['message'] = $errors;
    }
} else {
    $response['error'] = true;
    $response['message'] = "Insufficient parameters, please provide product data.";
}

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