<?php
// Unified dashboard for both Editors and Sub-admins
// Editors see only pages/features they have permission for
// Sub-admins see manage_pages by default

session_start();
require_once __DIR__ . '/db_config.php';

// Get user id from session
$userId = $_SESSION['user_id'] ?? null;
if (!$userId) {
    header('Location: admin_login.php');
    exit;
}

// Default
$isEditor = false;
$isSubadmin = false;
$editorPermissions = [];
$subadminPermissions = [];
$roleName = 'User';
$username = $_SESSION['username'] ?? 'User';

// Check subadmin
$subadminQ = $conn ? $conn->query("SELECT * FROM subadmins WHERE user_id = " . intval($userId) . " LIMIT 1") : false;
if ($subadminQ && $subadminQ->num_rows > 0) {
    $isSubadmin = true;
    $roleName = 'Sub-admin';
    $row = $subadminQ->fetch_assoc();
    $subadminPermissions = $row['permissions'] ? json_decode($row['permissions'], true) : [];
    $_SESSION['is_subadmin'] = true;
    $_SESSION['subadmin_permissions'] = $subadminPermissions;
}

// Check editor
$editorQ = $conn ? $conn->query("SELECT * FROM editors WHERE user_id = " . intval($userId) . " LIMIT 1") : false;
if ($editorQ && $editorQ->num_rows > 0) {
    $isEditor = true;
    $roleName = $isSubadmin ? 'Sub-admin' : 'Editor';
    $row = $editorQ->fetch_assoc();
    $editorPermissions = $row['permissions'] ? json_decode($row['permissions'], true) : [];
    $_SESSION['is_editor'] = true;
    $_SESSION['editor_permissions'] = $editorPermissions;
}

// Set permissions for dashboard logic
if ($isSubadmin) {
    $permissions = $subadminPermissions;
} elseif ($isEditor) {
    $permissions = $editorPermissions;
} else {
    // Not allowed
    header('Location: admin_login.php');
    exit;
}

// Helper: check if user has permission to access a feature
function hasPermission($featureName, $permissions) {
    if (empty($permissions)) return false;
    $perm = $permissions[$featureName] ?? 'none';
    return ($perm === 'editor' || $perm === 'subadmin');
}

// Define accessible pages based on role and permissions
// Only one initialization needed
$accessiblePages = [];
if ($isSubadmin) {
    // Subadmins get all admin dashboard features except 'Manage Users'
    $adminPages = [
        // ['name' => 'Dashboard', 'url' => 'admin_dashboard.php', 'icon' => '📊', 'perm' => 'dashboard'],
        
        ['name' => 'Manage Products', 'url' => 'admin_products.php', 'icon' => '🛍️', 'perm' => 'manage_products'],
        ['name' => 'Manage Orders', 'url' => 'admin_orders.php', 'icon' => '📦', 'perm' => 'manage_orders'],
        ['name' => 'Manage Marquee', 'url' => 'admin_manage_marquee.php', 'icon' => '📝', 'perm' => 'manage_marquee'],
        ['name' => 'Homepage Sections', 'url' => 'admin_manage_homepage.php', 'icon' => '🏠', 'perm' => 'manage_homepage'],
        ['name' => 'Category Carousel', 'url' => 'admin_manage_category_carousel.php', 'icon' => '🌀', 'perm' => 'manage_category_carousel'],
        ['name' => 'Slider Settings', 'url' => 'admin_manage_slider.php', 'icon' => '🎞️', 'perm' => 'manage_slider'],
        ['name' => 'Latest Products', 'url' => 'admin_manage_latest_products.php', 'icon' => '🆕', 'perm' => 'manage_latest_products'],
        ['name' => 'Video Section', 'url' => 'admin_manage_video.php', 'icon' => '🎬', 'perm' => 'manage_video'],
        ['name' => 'Footer Settings', 'url' => 'admin_manage_footer.php', 'icon' => '🦶', 'perm' => 'manage_footer'],
        ['name' => 'Manage Pages', 'url' => 'admin_manage_pages.php', 'icon' => '📄', 'perm' => 'manage_pages'],
        ['name' => 'Manage Carousel', 'url' => 'admin_manage_carousel.php', 'icon' => '📸', 'perm' => 'manage_carousel'],
        ['name' => 'Manage News', 'url' => 'admin_manage_news.php', 'icon' => '📰', 'perm' => 'manage_news'],
        // ['name' => 'Manage Categories', 'url' => 'admin_manage_categories.php', 'icon' => '🏷️', 'perm' => 'manage_categories'],
        
        ['name' => 'Manage SEO', 'url' => 'admin_seo_manager.php', 'icon' => '🔍', 'perm' => 'manage_seo'],
        ['name' => 'Manage Posts', 'url' => 'admin_blogs.php', 'icon' => '📝', 'perm' => 'manage_blogs'],
        // ['name' => 'Settings', 'url' => 'admin_manage_settings.php', 'icon' => '⚙️', 'perm' => 'manage_settings'],
   
        ];
    // Exclude 'Manage Users' page
    foreach ($adminPages as $page) {
        if ($page['url'] !== 'admin_manage_users.php') {
            $accessiblePages[] = $page;
        }
    }
} elseif ($isEditor) {
    require_once __DIR__ . '/helpers/permission_helper.php';
    $editorPages = [
        ['name' => 'Manage Products', 'url' => 'admin_products.php', 'icon' => '🛍️', 'perm' => 'manage_products'],
        ['name' => 'Manage Orders', 'url' => 'admin_orders.php', 'icon' => '📦', 'perm' => 'manage_orders'],
        ['name' => 'Manage Marquee', 'url' => 'admin_manage_marquee.php', 'icon' => '📝', 'perm' => 'manage_marquee'],
        ['name' => 'Homepage Sections', 'url' => 'admin_manage_homepage.php', 'icon' => '🏠', 'perm' => 'manage_homepage'],
        ['name' => 'Category Carousel', 'url' => 'admin_manage_category_carousel.php', 'icon' => '🌀', 'perm' => 'manage_category_carousel'],
        ['name' => 'Slider Settings', 'url' => 'admin_manage_slider.php', 'icon' => '🎞️', 'perm' => 'manage_slider'],
        ['name' => 'Latest Products', 'url' => 'admin_manage_latest_products.php', 'icon' => '🆕', 'perm' => 'manage_latest_products'],
        ['name' => 'Video Section', 'url' => 'admin_manage_video.php', 'icon' => '🎬', 'perm' => 'manage_video'],
        ['name' => 'Footer Settings', 'url' => 'admin_manage_footer.php', 'icon' => '🦶', 'perm' => 'manage_footer'],
        ['name' => 'Manage Pages', 'url' => 'admin_manage_pages.php', 'icon' => '📄', 'perm' => 'manage_pages'],
        ['name' => 'Manage Carousel', 'url' => 'admin_manage_carousel.php', 'icon' => '📸', 'perm' => 'manage_carousel'],
        ['name' => 'Manage News', 'url' => 'admin_manage_news.php', 'icon' => '📰', 'perm' => 'manage_news'],
        // ['name' => 'Manage Categories', 'url' => 'admin_manage_categories.php', 'icon' => '🏷️', 'perm' => 'manage_categories'],
        
        ['name' => 'Manage SEO', 'url' => 'admin_seo_manager.php', 'icon' => '🔍', 'perm' => 'manage_seo'],
        ['name' => 'Manage Posts', 'url' => 'admin_blogs.php', 'icon' => '📝', 'perm' => 'manage_blogs'],
        ];
    $accessiblePages = [];
    foreach ($editorPages as $page) {
        $permKey = $page['perm'];
        // Only show if editor has explicit permission for this feature (must be set and not 'none')
        if (isset($permissions[$permKey]) && $permissions[$permKey] !== 'none') {
            $accessiblePages[] = $page;
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($roleName); ?> Dashboard</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; 
            background: #f5f5f5; 
            color: #333; 
        }
        .container { max-width: 1200px; margin: 0 auto; padding: 24px; }
        .header { 
            background: #fff; 
            padding: 24px; 
            border-radius: 8px; 
            margin-bottom: 24px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .header h1 { font-size: 28px; margin-bottom: 8px; }
        .header .subtitle { color: #666; font-size: 14px; }
        .logout-btn {
            background: #f44336;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: background 0.2s;
        }
        .logout-btn:hover { background: #d32f2f; }
        .permissions-section {
            background: #fff;
            padding: 24px;
            border-radius: 8px;
            margin-bottom: 24px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .permissions-section h2 { font-size: 18px; margin-bottom: 8px; }
        .permissions-text { 
            font-size: 14px; 
            color: #666; 
            margin-bottom: 16px; 
            line-height: 1.6;
        }
        .permission-badge {
            display: inline-block;
            background: #FFC107;
            color: #333;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            margin-right: 8px;
        }
        .pages-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 16px;
        }
        .page-card {
            background: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            text-decoration: none;
            color: #333;
            transition: all 0.2s;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .page-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            border-color: #667eea;
            transform: translateY(-2px);
        }
        .page-card .icon { font-size: 32px; margin-bottom: 12px; }
        .page-card .name { font-weight: 600; font-size: 16px; margin-bottom: 8px; }
        .page-card .url { font-size: 12px; color: #999; }
        .no-access {
            background: #fff3cd;
            border: 1px solid #ffc107;
            padding: 16px;
            border-radius: 8px;
            color: #856404;
            margin-top: 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div>
                <h1><?php echo htmlspecialchars($roleName); ?> Dashboard</h1>
                <p class="subtitle">Welcome, <?php echo htmlspecialchars($username); ?></p>
            </div>
            <form action="admin_login.php" method="POST" style="display: inline;">
                <button type="submit" class="logout-btn">Logout</button>
            </form>
        </div>

        <div class="permissions-section">
            <!-- <h2>Your Access & Permission Levels</h2>
            <div class="permissions-text">
                <strong>Viewer:</strong> View only | 
                <strong>Editor:</strong> View, Create, Edit (no delete) | 
                <strong>Administrator:</strong> Full access (View, Add, Edit, Delete)
           
            </div> -->
            
            <?php if ($isEditor): ?>
                <h3 style="margin-top: 16px; margin-bottom: 8px;">Your Permissions</h3>
                <div>
                    <?php 
                    $permissionNames = [
                        'manage_posts' => 'Posts & Blog',
                        'manage_pages' => 'Pages',
                        'manage_products' => 'Products',
                        'manage_orders' => 'Orders',
                        'manage_carousel' => 'Carousel & Slider',
                        'manage_news' => 'News',
                        'manage_categories' => 'Categories',
                        'manage_users' => 'Users',
                        'manage_seo' => 'SEO',
                        'manage_settings' => 'Settings'
                    ];
                    
                    foreach ($permissionNames as $permKey => $permLabel) {
                        $perm = $permissions[$permKey] ?? 'none';
                        if ($perm !== 'none') {
                            echo '<span class="permission-badge">✓ ' . htmlspecialchars($permLabel) . '</span>';
                        }
                    }
                    ?>
                </div>
            <?php elseif ($isSubadmin): ?>
                <p class="permission-badge" style="display: inline-block;">✓ Manage Pages</p>
            <?php endif; ?>
        </div>

        <?php if (!empty($accessiblePages)): ?>
            <h2 style="margin-bottom: 16px;">Available Pages</h2>
            <div class="pages-grid">
                <?php foreach ($accessiblePages as $page): ?>
                    <a href="<?php echo htmlspecialchars($page['url']); ?>" class="page-card">
                        <div class="icon"><?php echo $page['icon']; ?></div>
                        <div class="name"><?php echo htmlspecialchars($page['name']); ?></div>
                        <div class="url"><?php echo htmlspecialchars($page['url']); ?></div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="no-access">
                No page access granted. Contact an administrator to assign permissions.
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
