<?php
/**
 * Permission Helper Functions
 * Provides permission checking functionality for the PetrolBunk application
 */

/**
 * Check if current user has a specific permission
 * @param string $permissionCode The permission code to check
 * @return bool True if user has permission, false otherwise
 */
function hasPermission($permissionCode) {
    global $con;
    
    if (!isset($_SESSION['uid'])) {
        return false;
    }
    
    $userId = (int)$_SESSION['uid'];
    $permissionCode = mysqli_real_escape_string($con, $permissionCode);
    
    // Check if user is admin (admins have all permissions)
    if (isset($_SESSION['usertype']) && $_SESSION['usertype'] == 'admin') {
        return true;
    }
    
    // Check permission through role
    $query = "SELECT COUNT(*) as has_perm
              FROM tblusers u
              INNER JOIN tblrolepermissions rp ON u.RoleID = rp.RoleID
              INNER JOIN tblpermissions p ON rp.PermissionID = p.ID
              WHERE u.ID = $userId AND p.PermissionCode = '$permissionCode'";
    
    $result = mysqli_query($con, $query);
    if (!$result) {
        return false;
    }
    
    $row = mysqli_fetch_assoc($result);
    return $row['has_perm'] > 0;
}

/**
 * Get all permissions for current user
 * @return array Array of permission codes
 */
function getUserPermissions() {
    global $con;
    
    if (!isset($_SESSION['uid'])) {
        return [];
    }
    
    $userId = (int)$_SESSION['uid'];
    
    // Admins get all permissions
    if (isset($_SESSION['usertype']) && $_SESSION['usertype'] == 'admin') {
        $query = "SELECT PermissionCode FROM tblpermissions";
    } else {
        // Get permissions through role
        $query = "SELECT DISTINCT p.PermissionCode
                  FROM tblusers u
                  INNER JOIN tblrolepermissions rp ON u.RoleID = rp.RoleID
                  INNER JOIN tblpermissions p ON rp.PermissionID = p.ID
                  WHERE u.ID = $userId";
    }
    
    $result = mysqli_query($con, $query);
    if (!$result) {
        return [];
    }
    
    $permissions = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $permissions[] = $row['PermissionCode'];
    }
    
    return $permissions;
}

/**
 * Check if user has any of the specified permissions
 * @param array $permissionCodes Array of permission codes
 * @return bool True if user has at least one permission
 */
function hasAnyPermission($permissionCodes) {
    foreach ($permissionCodes as $code) {
        if (hasPermission($code)) {
            return true;
        }
    }
    return false;
}

/**
 * Check if user has all of the specified permissions
 * @param array $permissionCodes Array of permission codes
 * @return bool True if user has all permissions
 */
function hasAllPermissions($permissionCodes) {
    foreach ($permissionCodes as $code) {
        if (!hasPermission($code)) {
            return false;
        }
    }
    return true;
}

/**
 * Redirect if user doesn't have permission
 * @param string $permissionCode Permission code to check
 * @param string $redirectUrl URL to redirect to (default: dashboard.php)
 */
function requirePermission($permissionCode, $redirectUrl = 'dashboard.php') {
    if (!hasPermission($permissionCode)) {
        $_SESSION['error'] = "You don't have permission to access this page.";
        header("Location: $redirectUrl");
        exit();
    }
}

/**
 * Get user's role information
 * @return array|null Role information or null if no role assigned
 */
function getUserRole() {
    global $con;
    
    if (!isset($_SESSION['uid'])) {
        return null;
    }
    
    $userId = (int)$_SESSION['uid'];
    
    $query = "SELECT r.* 
              FROM tblroles r
              INNER JOIN tblusers u ON r.ID = u.RoleID
              WHERE u.ID = $userId";
    
    $result = mysqli_query($con, $query);
    if (!$result || mysqli_num_rows($result) == 0) {
        return null;
    }
    
    return mysqli_fetch_assoc($result);
}

/**
 * Check if user has a specific role
 * @param string $roleCode Role code to check
 * @return bool True if user has the role
 */
function hasRole($roleCode) {
    $role = getUserRole();
    return $role && $role['RoleCode'] === $roleCode;
}

/**
 * Get permission categories with user's permissions
 * @return array Grouped permissions by category
 */
function getUserPermissionsByCategory() {
    global $con;
    
    if (!isset($_SESSION['uid'])) {
        return [];
    }
    
    $userId = (int)$_SESSION['uid'];
    
    if (isset($_SESSION['usertype']) && $_SESSION['usertype'] == 'admin') {
        $query = "SELECT * FROM tblpermissions ORDER BY Category, PermissionName";
    } else {
        $query = "SELECT DISTINCT p.*
                  FROM tblusers u
                  INNER JOIN tblrolepermissions rp ON u.RoleID = rp.RoleID
                  INNER JOIN tblpermissions p ON rp.PermissionID = p.ID
                  WHERE u.ID = $userId
                  ORDER BY p.Category, p.PermissionName";
    }
    
    $result = mysqli_query($con, $query);
    if (!$result) {
        return [];
    }
    
    $permissionsByCategory = [];
    while ($permission = mysqli_fetch_assoc($result)) {
        $category = $permission['Category'] ?? 'Other';
        if (!isset($permissionsByCategory[$category])) {
            $permissionsByCategory[$category] = [];
        }
        $permissionsByCategory[$category][] = $permission;
    }
    
    return $permissionsByCategory;
}

/**
 * Log permission check for audit (optional feature)
 * @param string $permissionCode Permission being checked
 * @param bool $granted Whether permission was granted
 */
function logPermissionCheck($permissionCode, $granted) {
    // Implement audit logging if needed
    // This is a placeholder for future audit functionality
    if (defined('ENABLE_PERMISSION_AUDIT') && ENABLE_PERMISSION_AUDIT) {
        global $con;
        $userId = isset($_SESSION['uid']) ? (int)$_SESSION['uid'] : 0;
        $grantedInt = $granted ? 1 : 0;
        $permissionCode = mysqli_real_escape_string($con, $permissionCode);
        
        $query = "INSERT INTO tblpermissionaudit (UserID, PermissionCode, Granted, CheckedAt) 
                  VALUES ($userId, '$permissionCode', $grantedInt, NOW())";
        mysqli_query($con, $query);
    }
}
?>
