<?php
	include_once __DIR__ . '/../config/dbconn.php';
	date_default_timezone_set('Asia/Manila');

	// Get JSON input
	$json = file_get_contents('php://input');
	$data = json_decode($json);
	
	// Get post data
	$trans = $data->trans;

	if ($trans == "addMaterialItems") {
		// Extract fields from the decoded JSON 
		$title 				= $data->title;
		$item_description	= $data->item_description;

		// Corrected variable name
		$str_qry_select = "SELECT code FROM material_items ORDER BY id DESC LIMIT 1";                  
		$runQuery = mysqli_query($con, $str_qry_select);

		// Initialize the nextHexCode
		$nextHexCode = '01'; // Default starting code if no items exist

		// If there are existing items, get the last code and increment it
		if ($items = mysqli_fetch_assoc($runQuery)) {
			$code = $items['code'];
			$decimalCode = hexdec($code);
			$nextDecimalCode = $decimalCode + 1;

			// Convert back to hex
			$nextHexCode = strtoupper(dechex($nextDecimalCode));

			// Ensure it is two characters
			if (strlen($nextHexCode) == 1) {
				$nextHexCode = '0' . $nextHexCode;
			}
		}

		// Prepare SQL query for inserting donation request
		$sql = "INSERT INTO material_items 
				( 
					code, title, item_description, created_at
				) VALUES (
					'$nextHexCode', '$title', '$item_description', Now()
				) ";

		// Execute the query
		if (mysqli_query($con, $sql)) {
			$response = new stdClass();
			$response->title = 'Request Successful';
			$response->description = 'Your request has been processed successfully!';
			$response->response_code = '0';
		} else {
			$response = new stdClass();
			$response->title = 'Request Failed';
			$response->description = 'We encountered an error while processing your request. Please try again!';
			$response->response_code = '3';
		} 

	} else if ($trans === "getMaterialItems") { 
		
		// Prepare the SQL query
		$sql = "SELECT * 
				FROM material_items 
				ORDER BY title ASC ";

		// Execute the query
		$runQuery = mysqli_query($con, $sql);
		$count_rows = mysqli_num_rows($runQuery);

		// If rows are found, return them as JSON
		if ($count_rows > 0) {
			$results = [];
			while ($record = mysqli_fetch_assoc($runQuery)) {
				$results[] = $record;
			}
			// Creating the response object
			$response = (object)null;
			$response->results = $results;
			$response->title = 'Successful';
			$response->description = 'Filter successfully!';
			$response->response_code = "0";
		} else {
			$response = (object)null;
			$response->title = 'Failed';
			$response->description = 'No record found!';
			$response->response_code = '2';
		}
		
	} else {
		// If invalid trans value
		$response = new stdClass();
		$response->title = 'Critical Error!';
		$response->description = 'Invalid transaction.';
		$response->response_code = '1';
	}

	// Send the response as JSON
	header('Content-Type: application/json');
	echo json_encode($response);
