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

// Initialize the response
$response = [];

// Check if the necessary POST data is present for credits
if (isset($_POST['creditsData'])) {
    $creditsData = $_POST['creditsData'];
    $creditsArray = json_decode($creditsData, true);
    $messages = [];

    foreach ($creditsArray as $row) {
        // Prepare the SQL statement for the credits table
        $stmt = $connect->prepare("INSERT INTO credits (product, date_taken, reason, source_of_fund, taken_by, title, phone, quantity, status, served_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        // Bind parameters to the SQL statement
        $stmt->bind_param("isssissisi", 
            $row["product"], 
            $row["date_taken"], 
            $row["reason"], 
            $row["source_of_fund"], 
            $row["taken_by"], 
            $row["title"], 
            $row["phone"], 
            $row["quantity"], 
            $row["status"], 
            $row["served_by"]
        );

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

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

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