<?php
/**
 * WIMAS - Main Secure Dynamic Router
 * Location: /index.php
 */
ob_start(); // CRITICAL: Holds HTML in memory so redirects can execute from inside modules!
error_reporting(E_ALL);

// Include Bootstrap using __DIR__ to guarantee it loads no matter what
require_once __DIR__ . '/config/bootstrap.php';

// =========================================================================
// 1. GLOBAL AUTHENTICATION CHECK
// =========================================================================
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// =========================================================================
// 2. SECURE DYNAMIC ROUTE DECODING
// =========================================================================
$module = 'dashboard';
$page   = 'list';
$params = [];

if (isset($_GET['s'])) {
    $decrypted = decrypt_url($_GET['s']);
    if ($decrypted) {
        parse_str($decrypted, $params);
        
        // MAGIC FIX: Pushes decrypted variables back into $_GET so standard PHP works perfectly
        $_GET = array_merge($_GET, $params); 
        $GLOBALS['request_data'] = $params;
        
        $module = $params['mod'] ?? 'dashboard';
        $page   = $params['page'] ?? 'list';
    } else {
        header("Location: index.php");
        exit;
    }
} else {
    // Fallback if no parameters are passed
    $module = $_GET['mod'] ?? 'dashboard';
    $page   = $_GET['page'] ?? 'list';
}

// Sanitize module and page names to prevent directory traversal hacks
$module = preg_replace('/[^a-zA-Z0-9_-]/', '', $module);
$page   = preg_replace('/[^a-zA-Z0-9_-]/', '', $page);

// =========================================================================
// 3. GLOBAL SECURITY GATEKEEPER (HRBAC Permission Engine)
// =========================================================================
$my_privs = ['can_view' => 0, 'can_add' => 0, 'can_edit' => 0, 'can_del' => 0];

if (isset($_SESSION['all_role_ids']) && !empty($_SESSION['all_role_ids'])) {
    // Sanitize the role list for a safe SQL IN clause
    $role_list = implode(',', array_map('intval', $_SESSION['all_role_ids']));
    $safe_module = $db->escape($module);
    
    // Find the current Menu ID based on the module folder requested
    $menu_sql = "SELECT CHILD_MENU_ID FROM TBL_CHILD_MENU WHERE MODULE_NAME = '$safe_module' LIMIT 1";
    $menu_res = $db->query($menu_sql);
    
    if ($menu_res && $menu_row = mysqli_fetch_assoc($menu_res)) {
        $cid = (int)$menu_row['CHILD_MENU_ID'];
        
        // Calculate the maximum permissions granted across ALL roles the user holds
        $perm_sql = "SELECT MAX(CAN_VIEW) as V, MAX(CAN_ADD) as A, MAX(CAN_EDIT) as E, MAX(CAN_DEL) as D 
                     FROM TBL_ROLE_PERMISSIONS 
                     WHERE MENU_ID = $cid AND ROLE_ID IN ($role_list)";
                     
        $perm_res = $db->query($perm_sql);
        if ($perm_res && $perm_row = mysqli_fetch_assoc($perm_res)) {
            $my_privs = [
                'can_view' => (int)$perm_row['V'],
                'can_add'  => (int)$perm_row['A'],
                'can_edit' => (int)$perm_row['E'],
                'can_del'  => (int)$perm_row['D']
            ];
        }
    }
}
// Expose the calculated privileges to the entire application
$GLOBALS['my_privs'] = $my_privs;


// =========================================================================
// 4. TARGET PATH CALCULATION
// =========================================================================
$target = BASE_PATH . "modules/{$module}/{$page}_{$module}.php";

// Fallback path check
if (!file_exists($target)) {
    $target = BASE_PATH . "modules/{$module}/{$page}.php";
}

// =========================================================================
// 5. UI ASSEMBLY & RENDERING
// =========================================================================
include BASE_PATH . 'includes/header.php';
include BASE_PATH . 'includes/navbar.php';
include BASE_PATH . 'includes/sidebar.php'; 

echo '<div class="content-wrapper p-3">'; 

    // --- GLOBAL SYSTEM MESSAGES ---
    $msg_id = $_GET['status'] ?? $params['status'] ?? null;
    if ($msg_id && isset($system_messages[$msg_id])) {
        $msg = $system_messages[$msg_id];
        echo "
        <div class='container-fluid'>
            <div class='alert alert-{$msg['type']} shadow-sm border-0 alert-dismissible fade show mb-4'>
                <i class='fas {$msg['icon']} mr-2'></i>
                <strong>{$msg['title']}:</strong> {$msg['msg']}
                <button type='button' class='close' data-dismiss='alert'>&times;</button>
            </div>
        </div>";
    }

    // --- LOAD THE MODULE ---
    if (file_exists($target)) {
        include $target;
    } else {
        // Module Missing UI
        echo '
        <div class="container-fluid d-flex align-items-center justify-content-center" style="min-height: 70vh;">
            <div class="text-center p-5 shadow-sm bg-white rounded-lg border-top border-primary" style="max-width: 500px; border-top-width: 4px !important;">
                <div class="mb-4"><i class="fas fa-tools fa-4x text-primary opacity-25"></i></div>
                <h2 class="font-weight-bold text-dark">UI Module Pending</h2>
                <p class="text-muted mb-4">The module file <code>modules/'.$module.'/'.$page.'.php</code> has not been created yet.</p>
            </div>
        </div>';
    }

echo '</div>'; 

include BASE_PATH . 'includes/footer.php';
?>