<?php
$username_error = null;
$success = null;
$UpdateUser = null;
$isUserFound = false;

function getUsers()
{
    $query = "SELECT * FROM users";
    $statement = PDO_CONNECTION->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll(PDO::FETCH_ASSOC);
    return $result;
}

if (isset($_POST['createUser'])) {
    $name =  trim($_POST['name']);
    $family =  trim($_POST['family']);
    $username =  trim($_POST['username']);
    $password = trim($_POST['password']);
    $type = trim($_POST['type']);
    $limit = trim($_POST['limit']);

    $success = registerUser($name, $family, $username, $password, $type, $limit);
}

function registerUser($name, $family, $username, $password, $type, $limit)
{
    // Hash the password
    $hash_pass = password_hash($password, PASSWORD_DEFAULT);

    try {
        // SQL query to insert a new user
        $sql = "INSERT INTO users (name, lastName, userName, password, role, request_limit) 
    VALUES (:name, :lastName, :userName, :password, :role, :request_limit)";

        // Prepare the statement
        $stmt = PDO_CONNECTION->prepare($sql);

        // Bind parameters
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':lastName', $family);
        $stmt->bindParam(':userName', $username); // Corrected this line
        $stmt->bindParam(':password', $hash_pass);
        $stmt->bindParam(':role', $type);
        $stmt->bindParam(':request_limit', $limit);
        $stmt->execute();
        return true;
    } catch (\Throwable $th) {
        global $username_error;
        $username_error = "نام کاربری قبلا در سیستم موجود است.";
        return false;
    }
}

if (basename($_SERVER['SCRIPT_FILENAME']) == 'updateUser.php') {
    if (isset($_GET['updateUser'])) {
        global $UpdateUser;

        $user_id = $_GET['updateUser'] ?? false;
        if (!$user_id) {
            die('کاربر مد نظر درسیستم موجود نمی باشد.');
        }

        $UpdateUser = getUser($user_id);

        if ($UpdateUser) {
            $isUserFound = true;
        }
    }

    if (isset($_POST['updateSelectedUser'])) {
        $userId =  trim($_POST['userId']);
        $name =  trim($_POST['name']);
        $family =  trim($_POST['family']);
        $username =  trim($_POST['username']);
        $password = trim($_POST['password']);
        $type = trim($_POST['type']);
        $limit = trim($_POST['limit']);
        $success = updateUser($userId, $name, $family, $username, $password = null, $type, $limit);
        $UpdateUser = getUser($user_id);
    } else {
    }
}

function updateUser($userId, $name, $family, $username, $password = null, $type, $limit)
{
    try {
        // Check if the username already exists for a different user
        $sql_check = "SELECT id FROM users WHERE userName = :userName AND id != :userId";
        $stmt_check = PDO_CONNECTION->prepare($sql_check);
        $stmt_check->bindParam(':userName', $username);
        $stmt_check->bindParam(':userId', $userId);
        $stmt_check->execute();

        if ($stmt_check->rowCount() > 0) {
            // Username exists for another user, return an error
            global $username_error;
            $username_error = "نام کاربری قبلا در سیستم موجود است."; // "Username already exists in the system."
            return false;
        }

        // Conditionally include password in the update query if it's provided
        $sql = "UPDATE users 
                SET name = :name, 
                    lastName = :lastName, 
                    userName = :userName, 
                    role = :role, 
                    request_limit = :request_limit";

        if (!empty($password)) {
            // Hash the password if it's provided
            $hash_pass = password_hash($password, PASSWORD_DEFAULT);
            $sql .= ", password = :password"; // Include password in the update query
        }

        $sql .= " WHERE id = :userId";

        // Prepare the statement
        $stmt = PDO_CONNECTION->prepare($sql);

        // Bind parameters
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':lastName', $family);
        $stmt->bindParam(':userName', $username);
        $stmt->bindParam(':role', $type);
        $stmt->bindParam(':request_limit', $limit);
        $stmt->bindParam(':userId', $userId); // Bind the user ID

        // Conditionally bind the password if it's being updated
        if (!empty($password)) {
            $stmt->bindParam(':password', $hash_pass);
        }

        // Execute the statement
        $stmt->execute();
        return true;
    } catch (\Throwable $th) {
        // Log the error and handle any exceptions
        error_log($th->getMessage());
        return false;
    }
}

function getUser($userId)
{
    $stmt = PDO_CONNECTION->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(":id", $userId);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    return $user;
}
