<?php
session_start();
require_once 'db/config.php';

function register_user($username, $password, $email) {
    try {
        $pdo = db();
        $password_hash = password_hash($password, PASSWORD_DEFAULT);
        
        // Get the default role ID (e.g., the role with the name 'Admin')
        $stmt = $pdo->prepare("SELECT id FROM roles WHERE name = 'Admin'");
        $stmt->execute();
        $role = $stmt->fetch();
        $default_role_id = $role ? $role['id'] : null;

        $stmt = $pdo->prepare("INSERT INTO users (username, password, role_id, email) VALUES (?, ?, ?, ?)");
        return $stmt->execute([$username, $password_hash, $default_role_id, $email]);
    } catch (PDOException $e) {
        // Handle duplicate username or other db errors
        error_log($e->getMessage());
        return false;
    }
}

function login_user($username, $password) {
    $pdo = db();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role_id'] = $user['role_id'];
        $_SESSION['email'] = $user['email'];
        return true;
    }
    return false;
}

function is_logged_in() {
    return isset($_SESSION['user_id']);
}

function logout_user() {
    session_unset();
    session_destroy();
}

function get_user_role_id() {
    return $_SESSION['role_id'] ?? null;
}

function hasPermission($permission) {
    if (!is_logged_in()) {
        return false;
    }

    $role_id = get_user_role_id();
    if (!$role_id) {
        return false;
    }

    // Super admin (role_id 1) has all permissions
    if ($role_id == 1) {
        return true;
    }

    $pdo = db();

    // Get the permission ID from the permission name
    $stmt = $pdo->prepare("SELECT id FROM permissions WHERE name = ?");
    $stmt->execute([$permission]);
    $permission_id = $stmt->fetchColumn();

    if (!$permission_id) {
        return false; // Permission not found
    }

    // Check if the role has the permission
    $stmt = $pdo->prepare("SELECT 1 FROM role_permissions WHERE role_id = ? AND permission_id = ?");
    $stmt->execute([$role_id, $permission_id]);

    return $stmt->fetchColumn() !== false;
}

?>