<?php
// includes/dashboard_helper.php

// Ensure session is started, as this file might be included in various places.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/**
 * Helper function to determine the appropriate dashboard link based on user role.
 * This is your existing function.
 * * @return string The appropriate absolute dashboard link (e.g., /IMS/dashboard.php)
 */
function getDashboardLink() {
    $basePath = '/IMS/'; // Base path for the application

    // Default dashboard link
    $dashboardLink = $basePath . 'views/dashboard/admin.php'; 
    
    if (isset($_SESSION['role'])) {
        switch ($_SESSION['role']) {
            case 'admin':
            case 'super_admin':
                $dashboardLink = $basePath . 'views/dashboard/admin.php';
                break;
            case 'controller':
                $dashboardLink = $basePath . 'views/dashboard/controller.php';
                break;
            case 'warehouse':
                $dashboardLink = $basePath . 'views/dashboard/warehouse.php';
                break;
            case 'branch_manager':
            case 'branch':
                $dashboardLink = $basePath . 'views/dashboard/branch.php';
                break;
            case 'sales_assistant':
            case 'sales':
                 $dashboardLink = $basePath . 'views/dashboard/assistant.php';
                break;
            default:
                // Fallback to a default page if role is unknown
                $dashboardLink = $basePath . 'index.php';
                break;
        }
    }
    
    return $dashboardLink;
}

/**
 * NEW FUNCTION
 * Fetches the branch name for a given user ID.
 * This is needed by the updated header.php.
 *
 * @param int $userId The ID of the user.
 * @param PDO $conn The database connection object.
 * @return string The name of the branch or a default string if not found.
 */
function getUserBranchName($userId, $conn) {
    try {
        // First, get the branch_id from the users table
        $stmt = $conn->prepare("SELECT branch_id FROM users WHERE user_id = ?");
        $stmt->execute([$userId]);
        $branchId = $stmt->fetchColumn();

        if ($branchId) {
            // Now, get the branch_name from the branches table
            $stmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
            $stmt->execute([$branchId]);
            $branchName = $stmt->fetchColumn();
            return $branchName ?: 'Unknown Branch';
        }
    } catch (PDOException $e) {
        // Log error for debugging purposes
        error_log("Error in getUserBranchName: " . $e->getMessage());
        return 'Error'; // Return a generic error message to the user
    }
    
    return 'No Branch Assigned';
}
?>

