<?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 == "addRequestDonation") {
		// Extract fields from the decoded JSON 
		$member_id 		= $data->member_id;
		$donation_type	= $data->donation_type;
		$item_id 		= $data->item_id;
		$item_quantity 	= $data->item_quantity;
		$amount 		= $data->amount;
		$purpose 		= $data->purpose;
		$location 		= $data->location;

		// Default status for new request
		$status = "Pending"; 
		if($donation_type=="Material"){
			$amount = 0;
		} else {  
			$item_id = 0;
			$item_quantity = 0; 
		}

		// Prepare SQL query for inserting donation request
		$sql = "INSERT INTO request 
				( 
					member_id, donation_type, item_id, item_quantity, amount, purpose, location, status, created_at
				) VALUES (
					'$member_id', '$donation_type', '$item_id', '$item_quantity', '$amount', '$purpose','$location','$status', 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->error = $sql.' :: '.mysqli_error($con);
			$response->title = 'Request Failed';
			$response->description = 'We encountered an error while processing your request. Please try again!';
			$response->response_code = '3';
		} 

	} else if ($trans === "getDonationRequest") { 
		
		// Extract fields from the decoded JSON
		$page = isset($data->page) ? $data->page : '';
		$status = isset($data->status) ? $data->status : '';
		$donation_type = isset($data->donation_type) ? $data->donation_type : '';
		$location = isset($data->location) ? $data->location : '';
			
		// Prepare the SQL query
		$sql = "SELECT *,
					(SELECT CONCAT(t.fname,' ',t.lname) FROM member t WHERE t.doc_number = member_id LIMIT 1) AS member_name,
					(SELECT t.email FROM member t WHERE t.doc_number = member_id LIMIT 1) AS member_email,
					(SELECT t.phone FROM member t WHERE t.doc_number = member_id LIMIT 1) AS member_phone,
					(SELECT CONCAT(t.location_st,' ',t.location_brgy,', ',t.location_city,', ',t.location_prov) FROM member t WHERE t.doc_number = member_id LIMIT 1) AS member_address,
					(SELECT t.title FROM material_items t WHERE t.id = item_id LIMIT 1) AS item_desc
				FROM request 
				WHERE status <> '' ";
		if($status=='' && $page!='request'){
			$sql .= " AND (status = 'Pending' OR status = 'Verified') ";
		}
		if($status!=''){
			$sql .= " AND status = '$status' ";
		}
		if($donation_type!=''){
			$sql .= " AND donation_type='$donation_type' ";
		}
		if($location!=''){
			$sql .= " AND location='$location' ";
		}
		$sql .= " 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 = new stdClass();
			$response->results = $results;
			$response->title = 'Successful';
			$response->description = 'Filter successfully!';
			$response->response_code = "0";
		} else {
            $response = new stdClass();
			$response->title = 'Failed';
			$response->description = 'No data found!';
			$response->response_code = '2';
		}
			
	} elseif ($trans == "updateRequestStatus") {
		
		$status = $data->status;
		$id = $data->id;

		$sql = "";

		if($status=='Verified'){
			$verified_by = $data->verified_by;
			$verified_date = date('Y-m-d H:i:s', strtotime($data->verified_date));
			
			// Prepare SQL query for updating  requests
			$sql = "UPDATE request 
					SET 
						status = '$status', 
						verified_date = '$verified_date', 
						verified_by = '$verified_by'
					WHERE id = '$id' ";
		} else if($status=='Approved'){
			$approved_by = $data->approved_by;
			$approved_date = date('Y-m-d H:i:s', strtotime($data->approved_date));

			// Prepare SQL query for updating  requests
			$sql = "UPDATE request 
					SET 
						status = '$status', 
						approved_date = '$approved_date', 
						approved_by = '$approved_by'
					WHERE id = '$id' ";
		} else if($status=='Denied'){
			$denied_by = $data->denied_by;
			$denied_date = date('Y-m-d H:i:s', strtotime($data->denied_date));

			// Prepare SQL query for updating  requests
			$sql = "UPDATE request 
					SET 
						status = '$status', 
						denied_date = '$denied_date', 
						denied_by = '$denied_by'
					WHERE id = '$id' ";
		} 
		
		// Execute the query
		if (mysqli_query($con, $sql)) {
			$response = new stdClass();
			$response->title = 'Successful';
			$response->description = 'Request has been '.$status.' 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';
			$response->description = mysqli_error($con);
		}

	} 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);
