<?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 TMP.*, user.name, user.nameZh
		FROM
			(SELECT submit_by, COUNT(*) AS cnt 
			FROM `taluozhanbu_submission` 
			WHERE status IN ('valid', 'pending_deletion') 
			GROUP BY submit_by 
			ORDER BY COUNT(*) DESC) AS TMP
		LEFT JOIN `user` ON user.username = TMP.submit_by
	";
	$result = $conn->query($sql);

	if ($result->num_rows > 0) {
		while ($row = $result->fetch_assoc()) {
			$temp = array(
				"submit_by" => $row['submit_by'],
				"name" => $row['name'],
				"nameZh" => $row['nameZh'],
				"cnt" => $row['cnt'],
			);

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

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