<?php
session_start();
require_once __DIR__ . '/config.php';

// Redirect to login if not authenticated
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit();
}

// Get current admin user data
$stmt = $conn->prepare("
    SELECT u.*, r.name as role_name 
    FROM admin_users u
    JOIN admin_roles r ON u.role_id = r.id
    WHERE u.id = ?
");
$stmt->bind_param("i", $_SESSION['admin_id']);
$stmt->execute();
$result = $stmt->get_result();
$admin = $result->fetch_assoc();

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

// Update last activity time
$_SESSION['last_activity'] = time();

// Check for permission
function hasPermission($permissionName) {
    global $conn, $admin;

    // Superadmin has all permissions
    if ($admin['role_name'] === 'superadmin') {
        return true;
    }

    $stmt = $conn->prepare("
        SELECT 1 FROM admin_role_permissions rp
        JOIN admin_permissions p ON rp.permission_id = p.id
        WHERE rp.role_id = ? AND p.name = ?
    ");
    $stmt->bind_param("is", $admin['role_id'], $permissionName);
    $stmt->execute();
    $result = $stmt->get_result();

    return $result->num_rows > 0;
}

// Check permission and redirect if not allowed
function requirePermission($permissionName) {
    if (!hasPermission($permissionName)) {
        $_SESSION['error'] = "You don't have permission to access this page.";
        header("Location: index.php");
        exit();
    }
}
?>
