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

// Prepare response array
$response = ["error" => false, "message" => ""];

// Read JSON input
$inputJSON = file_get_contents('php://input');
$creditData = json_decode($inputJSON, true);

if (is_array($creditData) && count($creditData) > 0) {
    // Prepare the insert query
    $insertQuery = "INSERT INTO credits (transID, product, date_taken, reason, source_of_fund, taken_by, title, phone, quantity, status, served_by, c_amount) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $connect->prepare($insertQuery);

    try {
        foreach ($creditData as $data) {
            // Bind parameters
            $stmt->bind_param(
                "iissssssissi",
                $data['transID'],
                $data['product'],
                $data['date_taken'],
                $data['reason'],
                $data['source_of_fund'],
                $data['taken_by'],
                $data['title'],
                $data['phone'],
                $data['quantity'],
                $data['status'],
                $data['served_by'],
                $data['c_amount']
            );
            $stmt->execute();
        }

        $response["message"] = "Credit data inserted successfully.";
    } catch (Exception $e) {
        $response["error"] = true;
        $response["message"] = "Error inserting data: " . $e->getMessage();
    }
} else {
    $response["error"] = true;
    $response["message"] = "Invalid or empty input data.";
}

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