<?php
require_once('config.php');

function parseGrant($grant) {
    if (preg_match("/GRANT (.*?) ON `(.*?)`\.`(.*?)`(?: \((.*?)\))?/", $grant, $matches)) {
        $permissions = preg_replace("/\(.*?\)/", "", $matches[1]);
        $database = htmlspecialchars($matches[2]);
        $table = htmlspecialchars($matches[3]);
        $columns = !empty($matches[4]) ? array_map('htmlspecialchars', array_map('trim', explode(',', $matches[4]))) : ["-"];
        return [$permissions, $database, $table, $columns];
    } elseif (preg_match("/GRANT (.*?) ON `(.*?)`\.\*/", $grant, $matches)) {
        $permissions = preg_replace("/\(.*?\)/", "", $matches[1]);
        $database = htmlspecialchars($matches[2]);
        return [$permissions, $database, "Minden tábla", ["-"]];
    }
    return ["Ismeretlen", "-", "-", ["-"]];
}



?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <?php if(!isset($_POST["user"])) {
    ?>

    <form action="" method="POST">
        <label>felhasználó neve: </label>
        <input type="text" name="user">
        <button type="submit">Felhasználó adatainak megjelenítése</button>
    </form>
    <?php    } else {
        $sql = "SHOW GRANTS FOR ".$_POST["user"].";";

        $result = $conn->query($sql);
        
        if ($result) {
            echo "<table border='1'>";
            echo "<tr><th>Felhasználó</th><th>Jogosultság</th><th>Adatbázis</th><th>Tábla</th><th>Oszlop</th></tr>";
            
            while ($row = $result->fetch_array(MYSQLI_NUM)) {
                foreach ($row as $grant) {
                    list($permissions, $database, $table, $columns) = parseGrant($grant);
                    echo "<tr>";
                    echo "<td>" . htmlspecialchars($_POST["user"]) . "</td>";
                    echo "<td>" . htmlspecialchars($permissions) . "</td>";
                    echo "<td>" . htmlspecialchars($database) . "</td>";
                    echo "<td>" . htmlspecialchars($table) . "</td>";
                    echo "<td>" . htmlspecialchars(implode(", ", $columns)) . "</td>";
                    echo "</tr>";
                }
            }
            
            echo "</table>";
        } else {
            echo "Hiba a lekérdezésben: " . $conn->error;
        }
        
        $conn->close();
        
        
    }
    ?>
    
</body>
</html>