<?php
session_start();
$_SESSION = array();

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 {
        session_regenerate_id(true); // Regenerate session ID upon successful login
        
        while ($row = $result->fetch_assoc()) {
            $_SESSION["username"] = $row["username"];
            $_SESSION["type"] = $row["type"];
            $_SESSION["last_activity"] = time();
            $_SESSION["logged_in"] = true;
            
			echo json_encode(["status" => "success", "redirect" => "dashboard.php?p=home&login=success"]);
        }
    }
}
?>