<?php
/**
 * User Dashboard Router
 * Central routing system for agents and super agents
 */

session_start();
require_once 'config.php';
require_once 'config_api.php';
require_once 'app/classes/ExternalAPIService.php';
require_once 'app/classes/BalanceHistory.php';
require_once 'app/classes/AdminNotificationManager.php';
require_once 'app/classes/SessionManager.php';
use App\classes\BalanceHistory;
use App\classes\SessionManager;

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$sessionRole = isset($_SESSION['role']) ? $_SESSION['role'] : null;

// SECURITY: Validate session to prevent session hijacking
$sessionManager = new SessionManager($conn);
$sessionValidation = $sessionManager->validateSession($user_id);

if (!$sessionValidation['valid']) {
    // Invalid session - force logout
    error_log("Invalid session detected - User ID: $user_id, Reason: " . $sessionValidation['reason']);
    $sessionManager->forceLogout();
    header('Location: login.php?error=session_invalid');
    exit();
}

// MULTI-LAYER SECURITY: Role-based access control
// Only 'agent' role is allowed here - 'store_owner' role goes to store dashboard
if ($sessionRole === 'store_owner') {
    // Store owners should be redirected to store dashboard (handled below)
    // But if they're here, verify and redirect
    require_once 'app/classes/StoreManager.php';
    $storeManager = new StoreManager($conn);
    $verification = $storeManager->verifyStoreOwner($user_id);
    if ($verification['valid']) {
        header('Location: pages/store_dashboard.php');
        exit();
    }
}
if ($sessionRole !== 'agent' && $sessionRole !== 'store_owner') {
    header('Location: login.php');
    exit();
}

// Get user information including store owner status
// SECURITY FIX: Use prepared statement to prevent SQL injection
$stmt = $conn->prepare("SELECT username, email, balance, role, is_store_owner, store_id FROM agents WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();
$balance = isset($user['balance']) ? $user['balance'] : 0;
$username = isset($user['username']) ? $user['username'] : 'Unknown';
$user_email = isset($user['email']) ? $user['email'] : '';
$role = isset($user['role']) ? $user['role'] : $sessionRole;
$isStoreOwner = isset($user['is_store_owner']) ? $user['is_store_owner'] : 0;

// MULTI-LAYER SECURITY: Only allow 'agent' role to access agent dashboard
if ($role !== 'agent') {
    // If user has 'store_owner' role, redirect to store dashboard
    if ($role === 'store_owner') {
        require_once 'app/classes/StoreManager.php';
        $storeManager = new StoreManager($conn);
        $verification = $storeManager->verifyStoreOwner($user_id);
        
        if ($verification['valid']) {
    header('Location: pages/store_dashboard.php');
    exit();
        } else {
            // Invalid store owner - fix the data
            error_log("Invalid store owner detected - User ID: $user_id, Reason: " . $verification['reason']);
            $fixStmt = $conn->prepare("UPDATE agents SET role = 'agent', is_store_owner = 0 WHERE id = ?");
            $fixStmt->bind_param("i", $user_id);
            $fixStmt->execute();
            $fixStmt->close();
        }
    } else {
        // Unknown role - redirect to login
        error_log("Unknown role detected - User ID: $user_id, Role: $role");
        header('Location: login.php');
        exit();
    }
}

// MULTI-LAYER CHECK: Verify agent is legitimate (not a store owner)
require_once 'app/classes/StoreManager.php';
$storeManager = new StoreManager($conn);
$agentVerification = $storeManager->verifyAgent($user_id);

if (!$agentVerification['valid']) {
    error_log("Invalid agent detected - User ID: $user_id, Reason: " . $agentVerification['reason']);
    
    // If user has is_store_owner = 1 but role = 'agent', fix it
    if ($isStoreOwner == 1 && $role === 'agent') {
        $fixStmt = $conn->prepare("UPDATE agents SET is_store_owner = 0 WHERE id = ?");
        $fixStmt->bind_param("i", $user_id);
        $fixStmt->execute();
        $fixStmt->close();
        error_log("Fixed is_store_owner flag for user ID: $user_id");
    }
}

// Initialize notification manager and get notifications for header display
$notificationManager = new AdminNotificationManager($conn);
$notifications = $notificationManager->getUserNotifications($user_id, $role, 5, 0, true);
$unreadCount = $notificationManager->getUnreadCount($user_id, $role);

// Initialize minimum top-up manager for all pages
require_once 'app/classes/MinimumTopupManager.php';
$minimumTopupManager = new MinimumTopupManager($conn);
$minimumTopupAmount = $minimumTopupManager->getMinimumAmount();
$isMinimumTopupEnabled = $minimumTopupManager->isMinimumTopupEnabled();

// Get the page to display
$page = isset($_GET['page']) ? $_GET['page'] : 'dashboard';

// Define allowed pages based on role
$allowedPages = [
    'dashboard' => true,
    'profile' => true,
    'balance_history' => true,
    'api_keys' => true,
    'change_password' => true,
    'today_orders' => true
];

// Validate page access
if (!isset($allowedPages[$page])) {
    $page = 'dashboard';
}

// Set page title and description
$pageTitles = [
    'dashboard' => 'Agent Dashboard',
    'profile' => 'Profile Management',
    'balance_history' => 'Balance History',
    'api_keys' => 'API Keys',
    'change_password' => 'Change Password',
    'today_orders' => 'Today\'s Orders'
];

$pageTitle = $pageTitles[$page] ?? 'Dashboard';
$pageDescription = "D-Bundles Stores $pageTitle - Professional data bundle management platform";

// Include the header
include 'includes/user_header.php';

// Include the appropriate page content
$pageFile = "pages/user_$page.php";
if (file_exists($pageFile)) {
    include $pageFile;
} else {
    // Fallback to dashboard if page doesn't exist
    include 'pages/user_dashboard.php';
}

// Include the footer
include 'includes/user_footer.php';
?>
