<?php
/**
 * Admin Portal Security Check
 * Include this at the top of EVERY admin page
 * 
 * Usage:
 * <?php
 * session_start();
 * require_once('../includes/admin-security.php');
 * ?>
 */

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

/**
 * Security Check 1: User must be logged in
 */
if (!isset($_SESSION['login']) || empty($_SESSION['login'])) {
    // Not logged in - redirect to ADMIN login page
    $_SESSION['admin_login_required'] = true;
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    header("location: ../admin-login.php");
    exit();
}

/**
 * Security Check 2: User must have authorized role
 */
$allowed_roles = ['admin', 'staff', 'sales', 'vendor'];
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], $allowed_roles)) {
    // Logged in but not authorized - redirect to admin login
    $_SESSION['errmsg'] = "Access denied. Privileged account required.";
    $_SESSION['admin_login_required'] = true;

    // Log unauthorized access attempt
    $log_file = __DIR__ . '/../logs/unauthorized_access.log';
    $log_dir = dirname($log_file);

    if (!file_exists($log_dir)) {
        @mkdir($log_dir, 0755, true);
    }

    $log_entry = sprintf(
        "[%s] Unauthorized admin access attempt: User ID: %s, Email: %s, IP: %s, Page: %s\n",
        date('Y-m-d H:i:s'),
        $_SESSION['id'] ?? 'N/A',
        $_SESSION['login'] ?? 'N/A',
        $_SERVER['REMOTE_ADDR'] ?? 'N/A',
        $_SERVER['REQUEST_URI'] ?? 'N/A'
    );

    @file_put_contents($log_file, $log_entry, FILE_APPEND);

    // Logout and redirect to admin login
    session_destroy();
    header("location: ../admin-login.php");
    exit();
}

// Session regeneration (Regenerate every 2 hours instead of 30 mins to avoid race conditions)
if (!isset($_SESSION['last_regeneration'])) {
    $_SESSION['last_regeneration'] = time();
} elseif (time() - $_SESSION['last_regeneration'] > 7200) {
    session_regenerate_id(true);
    $_SESSION['last_regeneration'] = time();
}

/**
 * Security Check 4: Check for session hijacking
 * Verify user agent and IP haven't changed
 */
$current_user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$current_ip = $_SERVER['REMOTE_ADDR'] ?? '';

if (!isset($_SESSION['user_agent'])) {
    $_SESSION['user_agent'] = $current_user_agent;
    $_SESSION['user_ip'] = $current_ip;
} else {
    // Allow IP changes (for mobile users switching networks)
    // But log them
    if ($_SESSION['user_agent'] !== $current_user_agent) {
        // User agent changed - log and logout
        error_log("Session Destroyed: UA Mismatch. Saved: " . $_SESSION['user_agent'] . " Current: " . $current_user_agent);
        session_destroy();
        header("location: ../admin-login.php");
        exit();
    }
}

/**
 * Set security headers for admin pages
 */
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

/**
 * Admin user info (cached for convenience)
 */
$admin_user = [
    'id' => $_SESSION['id'],
    'name' => $_SESSION['username'],
    'email' => $_SESSION['login'],
    'role' => $_SESSION['role']
];

/**
 * Helper function: Log admin actions
 */
function logAdminAction($action, $details = '')
{
    global $admin_user;

    $log_file = __DIR__ . '/../logs/admin_actions.log';
    $log_dir = dirname($log_file);

    if (!file_exists($log_dir)) {
        @mkdir($log_dir, 0755, true);
    }

    $log_entry = sprintf(
        "[%s] Admin: %s (%s) - Action: %s - Details: %s - IP: %s\n",
        date('Y-m-d H:i:s'),
        $admin_user['name'],
        $admin_user['email'],
        $action,
        $details,
        $_SERVER['REMOTE_ADDR'] ?? 'N/A'
    );

    @file_put_contents($log_file, $log_entry, FILE_APPEND);
}

/**
 * Check if user has specific permission
 * @param string $permission Permission key
 * @return bool True if authorized
 */
function has_permission($permission)
{
    global $admin_user;

    // If $admin_user is not set, try to build it from session
    if (!isset($admin_user) || !is_array($admin_user)) {
        if (!isset($_SESSION['role'])) {
            return false; // No role, no permission
        }
        $admin_user = [
            'role' => $_SESSION['role'] ?? '',
            'id' => $_SESSION['id'] ?? 0,
            'name' => $_SESSION['username'] ?? '',
            'email' => $_SESSION['login'] ?? ''
        ];
    }

    // Admin has all permissions
    if ($admin_user['role'] === 'admin') {
        return true;
    }

    // Role-based permissions
    $role_permissions = [
        'staff' => [
            'manage_products',
            'manage_orders',
            'view_reports',
            'manage_categories',
            'manage_inventory'
        ],
        'vendor' => [
            'manage_products',
            'view_my_sales',
            'manage_inventory'
        ],
        'sales' => [
            'manage_orders',
            'view_orders',
            'view_reports'
        ],
        'admin' => [
            // Admin gets all permissions through the check above at line 165
            // But listing them here for documentation
            'manage_products',
            'manage_orders',
            'view_reports',
            'manage_categories',
            'manage_inventory',
            'manage_users',
            'manage_locations',
            'manage_banners',
            'manage_staff',
            'manage_settings'
        ]
    ];

    if (isset($role_permissions[$admin_user['role']])) {
        return in_array($permission, $role_permissions[$admin_user['role']]);
    }

    return false;
}

// Success - Admin access granted
// Script continues to load the admin page
?>