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

$username = $data->username;
$password = $data->password;

$conn = connect_db();

$res = array();

if ($username == "" || $password == "") {
	$res["error"] = "Username or Password is empty";
} else {	
	if ($conn->connect_error) {
		die("Connection failed: " . $conn->connect_error);
	} else {
		$sql = "
			SELECT * 
			FROM `user`
			WHERE username = '" . $username . "'
			AND status = 1
			LIMIT 1
		";
		$result = $conn->query($sql);

		logfile("authenticate_" . date('Ymd') . ".log", $username . " attempted to login");

		if ($result->num_rows > 0) {
			while ($row = $result->fetch_assoc()) {
				if ($row["password"] == md5(md5(AUTH_SECRET1 . $password . AUTH_SECRET2))) {
					$update_sql = "
						UPDATE `user`
						SET last_login = CURRENT_TIMESTAMP
						WHERE username = '" . $username . "'
					";
					$stmt = $conn->prepare($update_sql);
					$stmt->execute();

					logfile("authenticate_" . date('Ymd') . ".log", $username . " login SUCCESS");

					$res["success"] = "Authenticated successfully";

					$res["username"] = $username;
					$res["password"] = $row["password"];
					$res["email"] = $row["email"];
					$res["role"] = $row["role"];
				} else {
					logfile("authenticate_" . date('Ymd') . ".log", $username . " login FAILED");

					$res["failed"] = "Authentication failed";
				}
			}
		} else {
			$sql2 = "
				SELECT * FROM `user`
				WHERE username = '" . $username . "'
				AND status = 0
				LIMIT 1
			";
			$result2 = $conn->query($sql2);

			if ($result2->num_rows > 0) {
				while ($row = $result2->fetch_assoc()) {
					$res["error"] = "User is inactive";
					logfile("authenticate_" . date('Ymd') . ".log", $username . " is INACTIVE");
				}
			} else {
				logfile("authenticate_" . date('Ymd') . ".log", $username . " NOT found");
				$res["error"] = "Username not found";
			}
		}
	}
}

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