<?php
ob_start();
require_once 'includes/auth.php';
require_once 'includes/functions.php';

requireLogin();

$default_page = 'dashboard';
if (hasRole('superadmin')) {
    $default_page = 'superadmin';
} elseif (hasRole('manager')) {
    $default_page = 'employees';
} elseif (hasRole(['supervisor', 'operator'])) {
    $default_page = 'worklist';
}

// Debug: error_log("Role: " . ($_SESSION['user_role'] ?? 'none') . " Default: " . $default_page);


// Parse Clean URLs
$request_uri = $_SERVER['REQUEST_URI'];
$base_path = dirname($_SERVER['SCRIPT_NAME']);
$path = str_replace($base_path, '', $request_uri);
$path = parse_url($path, PHP_URL_PATH);
$path = trim($path, '/');

$page = !empty($path) ? $path : $default_page;

// Handle old query string style for backward compatibility
if (isset($_GET['page']) && empty($path)) {
    $page = $_GET['page'];
}

// Prevent non-admin/owner/manager from accessing the dashboard directly
if ($page === 'dashboard' && hasRole(['supervisor', 'operator'])) {
    header("Location: " . url('worklist'));
    exit;
}

// Simple whitelist for pages
$allowed_pages = [
    'dashboard',
    'buyers',
    'suppliers',
    'inventory',
    'orders',
    'production-lines',
    'employees',
    'audit-logs',
    'worklist',
    'products',
    'company-settings',
    'branches',
    'machinery',
    'superadmin',
    'settings'
];

if (!in_array($page, $allowed_pages)) {
    $page = $default_page;
}

// Check roles for specific pages
if ($page === 'audit-logs' && !hasRole('owner')) {
    header("Location: " . url('dashboard', ['error' => 'unauthorized']));
    exit;
}

if ($page === 'worklist' && !hasRole(['manager', 'supervisor', 'operator'])) {
    header("Location: " . url('dashboard', ['error' => 'unauthorized']));
    exit;
}

// For now, just include the dashboard or placeholder
include 'views/layout/header.php';
include 'views/' . $page . '.php';
include 'views/layout/footer.php';
ob_end_flush();
