<?php
session_start();

require_once("dbconn.php");
require_once("phpFunctions.php");

if (isset($_POST["username"]) && isset($_POST["password"])) {
    $result = executeQuery($conn, "SELECT * FROM users WHERE BINARY username = ? AND password = ?", "ss", [$_POST["username"], $_POST["password"]]);
    
	if ($result === false) { 
		throw new Exception("Error executing query: " . $conn->error);
	} 
	
    if ($result->num_rows == 0) {
        echo json_encode(["status" => "error", "message" => "Invalid username or password."]);
    } else {
        while ($row = $result->fetch_assoc()) {
            if ($row["type"] == 2) {
                echo json_encode(["status" => "error", "message" => "The username you entered is not an admin."]);
            } else {        
                $_SESSION["superUser"] = $row["username"]; // Set the session variable to the username or another identifier
                
                // Get the current page URL from the POST data
                $currentPage = isset($_POST["currentPage"]) ? $_POST["currentPage"] : "defaultPage.php";
                
                echo json_encode(["status" => "success", "redirect" => $currentPage]);
            }
        }
    }
}
?>
