<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST");

require_once "../../config.php";

$json = file_get_contents("php://input");
$data = json_decode($json);

$conn = connect_db();

$res = array();

if ($conn->connect_error) {
	die('Connection failed: ' . $conn->connect_error);
} else {
	$sql = "
		SELECT `taluomima_submission`.*, `user`.name AS submitter_name, `user`.nameZh AS submitter_nameZh
		FROM `taluomima_submission` 
		LEFT JOIN `user` ON `user`.username = `taluomima_submission`.submit_by
		WHERE `taluomima_submission`.status IN ('valid', 'pending_deletion') 
		ORDER BY `taluomima_submission`.submission_datetime DESC;
	";
	$result = $conn->query($sql);

	if ($result->num_rows > 0) {
		while ($row = $result->fetch_assoc()) {
			$temp = array(
				"name" => $row['name'],
				"nameZh" => $row['nameZh'],
				"email" => $row['email'],
				"contact" => $row['contact'],
				"dob" => $row['dob'],
				"xingzuo" => $row['xingzuo'],
				"occupation" => $row['occupation'],
				"address" => $row['address'],
				"taluomima" => $row['taluomima'],
				"shengming" => $row['shengming'],
				"houtian" => $row['houtian'],
				"xingwei" => $row['xingwei'],
				"submission_datetime" => $row['submission_datetime'],
				"submit_by" => $row['submit_by'],
				"submitter_name" => $row['submitter_name'] . ' ' . $row['submitter_nameZh'],
			);

			array_push($res, $temp);
		}
	} else {
		$res["error"] = "Submission not found";
	}
}

$conn->close();
echo json_encode($res);
