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

// Function to generate a unique transaction token
function generateUniqueToken($connect) {
    do {
        // Generate a 20-character random alphanumeric string
        $token = bin2hex(random_bytes(10)); // 20-character length

        // Check if it exists in the database
        $checkQuery = "SELECT COUNT(*) FROM transactions WHERE trans_token = ?";
        $stmt = $connect->prepare($checkQuery);
        $stmt->bind_param("s", $token);
        $stmt->execute();
        $stmt->bind_result($count);
        $stmt->fetch();
        $stmt->close();
    } while ($count > 0); // Repeat if token exists

    return $token;
}

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

// Read JSON input from POST request
$inputJSON = file_get_contents('php://input');
$requestData = json_decode($inputJSON, true);

if (isset($requestData['data']) && is_array($requestData['data'])) {
    // Prepare the SQL statement
    $insertQuery = "INSERT INTO transactions (trans_amount, takenBy, trans_date, trans_type, servedBy, paymentMethod, referenceID, trans_token, trans_details) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $connect->prepare($insertQuery);

    try {
        foreach ($requestData['data'] as $transaction) {
            // Generate a unique transaction token
            $trans_token = generateUniqueToken($connect);

            // Bind parameters
            $stmt->bind_param(
                "isssissss",
                $transaction['trans_amount'],
                $transaction['takenBy'],
                $transaction['trans_date'],
                $transaction['trans_type'],
                $transaction['servedBy'],
                $transaction['paymentMethod'],
                $transaction['referenceID'],
                $trans_token,  // Use generated unique token
                $transaction['trans_details']
            );
            $stmt->execute();
        }

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

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