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

$nian_ID = $data->nian_ID;
$yue_ID = $data->yue_ID;
$ri_ID = $data->ri_ID;
$shichen_ID = $data->shichen_ID;

$conn = connect_db();

$res = array();

if ($conn->connect_error) {
	die('Connection failed: ' . $conn->connect_error);
} else {
	$nian_liangshu = 0;
	$yue_liangshu = 0;
	$ri_liangshu = 0;
	$shichen_liangshu = 0;

	$nian_sql = "
		SELECT liangshu 
		FROM `liangshu_nian` 
		WHERE ID = " . $nian_ID . " 
		LIMIT 1
	";
	$nian_result = $conn->query($nian_sql);

	if ($nian_result->num_rows > 0) {
		while ($nian_row = $nian_result->fetch_assoc()) {
			$nian_liangshu = $nian_row['liangshu'];
		}
	}

	$yue_sql = 'SELECT liangshu FROM `liangshu_yue` WHERE ID = ' . $yue_ID . ' LIMIT 1';
	$yue_result = $conn->query($yue_sql);

	if ($yue_result->num_rows > 0) {
		while ($yue_row = $yue_result->fetch_assoc()) {
			$yue_liangshu = $yue_row['liangshu'];
		}
	}

	$ri_sql = 'SELECT liangshu FROM `liangshu_ri` WHERE ID = ' . $ri_ID . ' LIMIT 1';
	$ri_result = $conn->query($ri_sql);

	if ($ri_result->num_rows > 0) {
		while ($ri_row = $ri_result->fetch_assoc()) {
			$ri_liangshu = $ri_row['liangshu'];
		}
	}

	$shichen_sql = 'SELECT liangshu FROM `liangshu_shichen` WHERE ID = ' . $shichen_ID . ' LIMIT 1';
	$shichen_result = $conn->query($shichen_sql);

	if ($shichen_result->num_rows > 0) {
		while ($shichen_row = $shichen_result->fetch_assoc()) {
			$shichen_liangshu = $shichen_row['liangshu'];
		}
	}

	$total_liangshu = $nian_liangshu + $yue_liangshu + $ri_liangshu + $shichen_liangshu;

	$sql = 'SELECT liangshu, ming, gejue1, gejue2, gejue, zhujie FROM `chenggu_result` WHERE weight = ' . $total_liangshu . ' LIMIT 1';
	$result = $conn->query($sql);

	if ($result->num_rows > 0) {
		while ($row = $result->fetch_assoc()) {
			$res["liangshu"] = $row["liangshu"];
			$res["ming"] = $row["ming"];
			$res["gejue1"] = $row["gejue1"];
			$res["gejue2"] = $row["gejue2"];
			$res["gejue"] = $row["gejue"];
			$res["zhujie"] = $row["zhujie"];
		}
	}
}

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