<?php include('config.php');

// Check if session is already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// TEMP: use logged-in user later - Remove this line in production
if (!isset($_SESSION['admin_id'])) {
    $_SESSION['admin_id'] = 1;
}

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

$admin_id = $_SESSION['admin_id'];

// Get admin details
$sql = "SELECT * FROM admins WHERE id = '$admin_id' AND is_active = 1";
$result = mysqli_query($conn, $sql);
$admin = mysqli_fetch_assoc($result);

if (!$admin) {
    session_destroy();
    header("Location: login.php");
    exit();
}

// Store admin info in session
$_SESSION['admin_name'] = $admin['name'];
$_SESSION['admin_email'] = $admin['email'];
$_SESSION['admin_role'] = $admin['role'];

// Helper function to check permissions
function checkPermission($conn, $admin_role, $module, $permission) {
    $sql = "SELECT $permission FROM admin_permissions 
            WHERE role = '$admin_role' AND module = '$module'";
    $result = mysqli_query($conn, $sql);
    
    if ($row = mysqli_fetch_assoc($result)) {
        return $row[$permission] == 1;
    }
    return false;
}

// Helper function to log admin activity
function logAdminActivity($conn, $admin_id, $action, $description = null, 
                         $module = null, $affected_id = null, $affected_table = null) {
    
    // Get admin details
    $sql = "SELECT name, role FROM admins WHERE id = '$admin_id'";
    $result = mysqli_query($conn, $sql);
    $admin = mysqli_fetch_assoc($result);
    
    if ($admin) {
        $admin_name = mysqli_real_escape_string($conn, $admin['name']);
        $admin_role = mysqli_real_escape_string($conn, $admin['role']);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_agent = mysqli_real_escape_string($conn, $_SERVER['HTTP_USER_AGENT']);
        $action = mysqli_real_escape_string($conn, $action);
        $description = mysqli_real_escape_string($conn, $description);
        $module = mysqli_real_escape_string($conn, $module);
        $affected_id = intval($affected_id);
        $affected_table = mysqli_real_escape_string($conn, $affected_table);
        
        $sql = "INSERT INTO admin_activities 
                (admin_id, admin_name, admin_role, action, description, module, 
                 ip_address, user_agent, affected_id, affected_table, created_at) 
                VALUES 
                ('$admin_id', '$admin_name', '$admin_role', '$action', '$description', '$module',
                 '$ip_address', '$user_agent', '$affected_id', '$affected_table', NOW())";
        
        return mysqli_query($conn, $sql);
    }
    return false;
}

// Check permission for current page
$current_page = basename($_SERVER['PHP_SELF']);
$module_map = [
    'index.php' => 'dashboard',
    'dashboard.php' => 'dashboard',
    'users.php' => 'users',
    'users_pending.php' => 'users',
    'users_verified.php' => 'users',
    'users_rejected.php' => 'users',
    'kyc_documents.php' => 'users',
    'bot_plans.php' => 'trading_bots',
    'bot_subscriptions.php' => 'trading_bots',
    'bot_transactions.php' => 'trading_bots',
    'bot_performance.php' => 'trading_bots',
    'deposits.php' => 'transactions',
    'withdrawals.php' => 'transactions',
    'all_transactions.php' => 'transactions',
    'profit_loss.php' => 'transactions',
    'revenue.php' => 'financial',
    'subscription_analytics.php' => 'financial',
    'commission_report.php' => 'financial',
    'financial_summary.php' => 'financial',
    'support_tickets.php' => 'support',
    'faq_management.php' => 'support',
    'feedback.php' => 'support',
    'activity_logs.php' => 'support',
    'referrals.php' => 'referrals',
    'referral_settings.php' => 'referrals',
    'referral_bonuses.php' => 'referrals',
    'top_referrers.php' => 'referrals',
    'system_settings.php' => 'settings',
    'payment_settings.php' => 'settings',
    'email_settings.php' => 'settings',
    'admin_management.php' => 'settings',
    'daily_report.php' => 'reports',
    'monthly_report.php' => 'reports',
    'user_activity_report.php' => 'reports',
    'trading_report.php' => 'reports',
    'view_user.php' => 'reports'
];

$current_module = $module_map[$current_page] ?: 'dashboard';

// Check if admin has view permission for this module
if (!checkPermission($conn, $_SESSION['admin_role'], $current_module, 'can_view')) {
    header("Location: unauthorized.php");
    exit();
}

// Log page view activity
logAdminActivity($conn, $admin_id, 'Page View', "Viewed $current_page", $current_module);

?>