<?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 == "addDonationRequest") {
		
		// Extract fields from the decoded JSON 
		$donation_id 		= $data->donation_id;
		$material_description = $data->material_description;
		$quantity 			= $data->quantity;
		$requester_id 		= $data->requester_id;
		$requester_name 	= $data->requester_name;
		$random_id 			= $data->random_id;;
		$location 			= $data->location;
		$donorCompanyId 	= $data->donorCompanyId;
		$donorCompanyName 	= $data->donorCompanyName;


		// Default status for new requests
		$status = "Pending"; 

		// Generate a unique ID for donation request
		$randnum1 = rand(10, 99);
		$randnum2 = rand(100, 999);
		$request_id = $randnum1 . date("mYdiHs") . $randnum2;


		// Prepare SQL query for inserting donation requests
		$sql = "INSERT INTO donation_requests 
				( 
					donation_id, material_description, quantity, requester_id, requester_name, random_id, status, location, donorCompanyId, donorCompanyName, requesting_organization
				) VALUES (
					'$donation_id', '$material_description', '$quantity', '$requester_id', '$requester_name','$random_id', '$status', '$location','$donorCompanyId','$donorCompanyName','$donorCompanyName'
				)";

		// Execute the query
		if (mysqli_query($con, $sql)) {
			$response = new stdClass();
			$response->message = 'Donation request inserted successfully.';
			$response->response_code = '0';
		} else {
			$response = new stdClass();
			$response->message = 'Failed to insert donation request.';
			$response->response_code = '3';
			$response->description = mysqli_error($con);
		} 
		
	} else if ($trans === "getDonationRequests" ) { 
		$requester_id = $data->requester_id;

		if (isset($requester_id)) {
			$status = isset($data->status)?$data->status:'';
			
			// Prepare the SQL query to fetch donation requests for the given requester_id
			$sql = "SELECT * FROM donation_requests WHERE requester_id = '$requester_id' ";
			if($status!=''){
			$sql .= " AND status='$status' ";
			}
			$sql .= " ORDER BY request_timestamp DESC";

			// 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 = new stdClass();
				$response->results = $results;
				$response->response_code = "0";
			} else {
				// If no requests are found
				$response = new stdClass();
				$response->message = 'No Donation Requests Found!';
				$response->response_code = '2';
			}
		} else {
			// If missing requester_id
			$response = new stdClass();
			$response->message = 'Critical Error! Missing required parameter.';
			$response->response_code = '1';
		}
		
	} else if ($trans === "getDonationRequestsUnderVerification" ) { 
		$requester_id = $data->requester_id;

		if (isset($requester_id)) { 
			
			// Prepare the SQL query to fetch donation requests for the given requester_id
			$sql = "SELECT * 
					FROM donation_requests 
					WHERE requester_id = '$requester_id' AND (status='Verified' OR status='Approved') 
					ORDER BY request_timestamp DESC ";

			// 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 = new stdClass();
				$response->results = $results;
				$response->response_code = "0";

			} else {
				// If no requests are found
				$response = new stdClass();
				$response->message = 'No Donation Requests Found!';
				$response->response_code = '2';
			}
		} else {
			// If missing requester_id
			$response = new stdClass();
			$response->message = 'Critical Error! Missing required parameter.';
			$response->response_code = '1';
		}

		
	} else if ($trans === "getDonationsList" ) { 
		
		// Extract fields from the decoded JSON
		$location = $data->location;
		
		// Prepare the SQL query based on whether a limit is provided
		$sql = "SELECT * 
				FROM donations 
				WHERE location LIKE '$location' 
				ORDER BY created_at DESC ";
		 
		// 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->response_code = "0";

			// Sending JSON response
		} else {
			// If no donations are found
			$response = (object)null;
			$response->message = 'No Donations Found!';
			$response->description = "";
			$response->response_code = '2';
		}
		
		
	} else if ($trans === "getDonationsByLocation" ) { 
		
		// Extract fields from the decoded JSON
		$location = $data->location;
		
		// Prepare the SQL query based on whether a limit is provided
		$sql = "SELECT * 
				FROM donateItemPerCompany 
				WHERE location LIKE '$location'				
				ORDER BY date_ts DESC ";
		 
		// 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->response_code = "0";

			// Sending JSON response
		} else {
			// If no donations are found
			$response = (object)null;
			$response->message = 'No Donations Found!';
			$response->description = "";
			$response->response_code = '2';
		}
		
	} elseif ($trans == "claimedRequests") {
		
		$requester_id = $data->requester_id;
		$random_id = $data->random_id; 
		
		// Prepare SQL query for updating  requests
		$sql = "UPDATE donation_requests 
				SET status='Claimed', claim_date=Now()
				WHERE requester_id='$requester_id' AND random_id='$random_id' AND status='Approved'";

        // Execute the query
        if (mysqli_query($con, $sql)) {
            $response = new stdClass();
            $response->message = 'Request has claimed successfully.';
            $response->response_code = '0';
        } else {
            $response = new stdClass();
            $response->message = 'Failed to claimed this request.';
            $response->response_code = '3';
            $response->description = mysqli_error($con);
        }

	} else if ($trans == "structure") {
		 // $sql = "ALTER TABLE donation_requests MODIFY COLUMN status ENUM('Pending', 'Verified', 'Approved', 'Denied', 'Claimed') NOT NULL";
		// $sql = "ALTER TABLE donation_requests ADD COLUMN availed_date DATETIME DEFAULT NULL;";
		// mysqli_query($con, $sql);
    
	
		$sql = "SHOW FULL COLUMNS FROM donation_requests";
		
		// Execute the query
		$result = mysqli_query($con, $sql);
		if ($result->num_rows > 0) {
	 
			while ($row = $result->fetch_assoc()) {
				echo "Field: " . $row["Field"] . " - Type: " . $row["Type"] . " - Default: " . $row["Default"] . "\n";
				// echo json_encode($row) . "\n";
			}
			
			$response = new stdClass();
			$response->message = 'Donation request inserted successfully.';
			$response->response_code = '0';

		} else {
			$response = new stdClass();
			$response->message = 'Failed to insert donation request.';
			$response->response_code = '3';
			$response->description = mysqli_error($con);
		}
		
	} else {
		// If invalid trans value
		$response = new stdClass();
		$response->message = 'Critical Error! Invalid transaction.';
		$response->response_code = '1';
	}

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