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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Initialize the response
$response = [];

// Check if the necessary POST data is present for transactions
if (isset($_POST['transactionsData'])) {
    $transactionsData = $_POST['transactionsData'];
    $transactionsArray = json_decode($transactionsData, true);
    
    // Check if JSON decoding was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        $response['error'] = true;
        $response['message'] = "JSON decoding error: " . json_last_error_msg();
        echo json_encode($response);
        exit;
    }

    // Verify that we have an array to process
    if (!is_array($transactionsArray)) {
        $response['error'] = true;
        $response['message'] = "Invalid transactions data format.";
        echo json_encode($response);
        exit;
    }

    $messages = [];

    foreach ($transactionsArray as $row) {
        // Prepare the SQL statement for the transactions table
        $stmt = $connect->prepare("INSERT INTO transactions (productCode, quantity, amount, releaseDate, releaseType, servedBy) VALUES (?, ?, ?, ?, ?, ?)");

        // Check if statement preparation was successful
        if (!$stmt) {
            $response['error'] = true;
            $response['message'] = "Statement preparation failed: " . $connect->error;
            echo json_encode($response);
            exit;
        }
        
        // Bind parameters to the SQL statement
        $stmt->bind_param("ssssss", 
            $row["productCode"], 
            $row["quantity"], 
            $row["amount"], 
            $row["releaseDate"], 
            $row["releaseType"], 
            $row["servedBy"]
        );

        // Execute the prepared statement and capture the response
        if ($stmt->execute()) {
            $messages[] = "Transaction record for product code " . $row["productCode"] . " added successfully.";
        } else {
            $messages[] = "Error adding transaction record for product code " . $row["productCode"] . ": " . $stmt->error;
        }
    }

    $response['error'] = false;
    $response['message'] = $messages;
} else {
    $response['error'] = true;
    $response['message'] = "Insufficient parameters for transactions data.";
}

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