<?php

// Function Displays error as an alert on RDT frontend
function rdtErrorHandler(int $errorNum, string $errorString, string $errorFile, int $errorLine ): void
{
	exit("FAIL- $errorNum, $errorString, $errorFile at line $errorLine");
}


/**
 * Sends a POST request to a TOMCAT service and returns the response
 *
 * @param string $serviceUri The URI of the TOMCAT service.
 * @param array $data The data to be sent in the request body.
 * @return array Returns an array containing the response data, error message, HTTP code, and posted data.
 */
function tomcatService(string $serviceUri, array $data): array
{
	// Encodes data array to JSON format
	try
	{
		$jsonData = json_encode($data);
	}
	catch (Exception $e)
	{
		exit('FAIL-JSON encode failed');
	}

	// Initialises cURL
	$ch = curl_init();

	// Sets cURL options
	$options = [
		CURLOPT_URL => $serviceUri,
		CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
		CURLOPT_POST => 1,
		CURLOPT_POSTFIELDS => $jsonData,
		CURLOPT_RETURNTRANSFER => true
	];
	curl_setopt_array($ch, $options);

	// Executes the cURL request and creates response array
	$response = [
		'responseData' => curl_exec($ch),
		'error' => curl_error($ch),
		'httpCode' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
		'postedData' => $jsonData
	];

	// Closes the cURL resource
	curl_close($ch);

	// Returns response array
	return $response;
}

/**
 * Retrieves the weight of a part based on the provided part number.
 *
 * @param string $partNumber The part number for which to retrieve the weight.
 * @param mysqli $connection A MySQLi connection object.
 * @return string The weight of the specified part.
 */
function getPartNumberWeight(string $partNumber, mysqli $connection): string
{
    $query = 'SELECT
            part.weight AS part_weight
        FROM part
        WHERE part.part_number = ?';
    $stmt = $connection->prepare($query);
    $stmt->bind_param('s', $partNumber);
    $stmt->execute();
    $result = $stmt->get_result();
    ['part_weight' => $partWeight] = $result->fetch_assoc();
    $result->free();
    $stmt->close();
    return $partWeight ? (string) $partWeight : '0';
}