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

$module_link = $data->module_link;
$username = $data->username;
$role = $data->role;

$conn = connect_db();

$res = array();

if ($username == "" || $role == "") {
	$res["error"] = "Username and Role are required.";
} else {
	if ($conn->connect_error) {
		die("Connection failed: " . $conn->connect_error);
	} else {
		$sql1 = "
			SELECT * 
			FROM `user`
			WHERE username = '" . $username . "'
			AND role = '" . $role . "'
			LIMIT 1
		";
		$result1 = $conn->query($sql1);

		if ($result1->num_rows > 0) {
			while ($row1 = $result1->fetch_assoc()) {
				$sql2 = "
					SELECT * 
					FROM `module`
					WHERE link = '" . $module_link . "'
					LIMIT 1
				";
				$result2 = $conn->query($sql2);

				if ($result2->num_rows > 0) {
					while ($row2 = $result2->fetch_assoc()) {
						$res["access"] = stripos($row2["access"], $role);
					}
				} else {
					$res["error"] = "Module not found";
				}
			}
		} else {
			$res["error"] = "User not found";
		}
	}
}

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