<?php
// Start or resume the session
session_start();

header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

// Check if the user is logged in and if their level is "Admin"
if (!isset($_SESSION['username']) || $_SESSION['level'] != 'Admin') {
    header("Location: index.php");
    exit;
}

// Connecting to the database
require_once '/my_custom_url/PRIVATE/db_config.php';
$conn = new mysqli($servername, $username, $password, $dbname);

// Checking the connection
if ($conn->connect_error) {
    die("Connection failure: " . $conn->connect_error);
}

// Form processing
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $level = $_POST['level'];

    // Check if username already exists
    $stmt = $conn->prepare("SELECT usernameIndex FROM USERS WHERE usernameIndex = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Username already exists
        echo "This username already exists.";
        $stmt->close();
    } else {
        // Username is available, continue with inserting new user
        // Password hash
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // Preparing the insert query
        $stmt = $conn->prepare("INSERT INTO USERS (usernameIndex, password, emailIndex, level) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $username, $hashed_password, $email, $level);

        // Executing the query
        if ($stmt->execute()) {
            // Success, redirect to admin.php
            header("Location: admin.php");
            exit;
        } else {
            echo "Erreur: " . $stmt->error;
        }

        $stmt->close();
    }
}

// Closing connection
if (isset($conn)) {
    $conn->close();
}
?>
