<?php
/**
 * Enterprise HRM ERP System - Role Management Dashboard
 * Centralized dashboard for managing roles, permissions, and assignments
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

// Check if user is Super Admin
startSession();

$roleCode = $_SESSION['role_code'] ?? '';
if (empty($roleCode) && isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT r.role_code 
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE u.user_id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);
        $userRole = $stmt->fetch();
        if ($userRole && !empty($userRole['role_code'])) {
            $roleCode = $userRole['role_code'];
            $_SESSION['role_code'] = $roleCode;
        }
    } catch (Exception $e) {
        error_log("Error loading role_code: " . $e->getMessage());
    }
}

if (strtolower($roleCode) !== 'super_admin') {
    $_SESSION['error'] = 'Only Super Admin can access role management dashboard.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Role Management Dashboard';
$currentModule = 'settings';

// Get statistics
try {
    $db = getDB();
    
    // Total roles count
    $stmt = $db->query("SELECT COUNT(*) FROM roles");
    $totalRoles = $stmt->fetchColumn();
    
    // Custom roles count
    $stmt = $db->query("SELECT COUNT(*) FROM roles WHERE is_system_role = 0");
    $customRoles = $stmt->fetchColumn();
    
    // Total permissions count
    $stmt = $db->query("SELECT COUNT(*) FROM permissions");
    $totalPermissions = $stmt->fetchColumn();
    
    // Total users count
    $stmt = $db->query("SELECT COUNT(*) FROM users WHERE user_status = 'active'");
    $totalUsers = $stmt->fetchColumn();
    
    // Users by role
    $stmt = $db->prepare("
        SELECT r.role_id, r.role_name, r.role_code, COUNT(u.user_id) as user_count
        FROM roles r
        LEFT JOIN users u ON r.role_id = u.role_id AND u.user_status = 'active'
        GROUP BY r.role_id
        ORDER BY user_count DESC, r.role_name
    ");
    $stmt->execute();
    $usersByRole = $stmt->fetchAll();
    
    // Recent roles
    $stmt = $db->prepare("
        SELECT r.*, COUNT(DISTINCT u.user_id) as user_count,
               COUNT(DISTINCT rp.permission_id) as permission_count
        FROM roles r
        LEFT JOIN users u ON r.role_id = u.role_id
        LEFT JOIN role_permissions rp ON r.role_id = rp.role_id
        GROUP BY r.role_id
        ORDER BY r.created_at DESC
        LIMIT 10
    ");
    $stmt->execute();
    $recentRoles = $stmt->fetchAll();
    
    // Permissions by module
    $stmt = $db->prepare("
        SELECT permission_module, COUNT(*) as count
        FROM permissions
        GROUP BY permission_module
        ORDER BY count DESC
    ");
    $stmt->execute();
    $permissionsByModule = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Dashboard error: " . $e->getMessage());
    $totalRoles = 0;
    $customRoles = 0;
    $totalPermissions = 0;
    $totalUsers = 0;
    $usersByRole = [];
    $recentRoles = [];
    $permissionsByModule = [];
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Role Management Dashboard</h2>
        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-primary">Manage Roles</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles_create.php" class="btn btn-primary">Create Role</a>
            <a href="<?php echo BASE_URL; ?>/admin/permissions.php" class="btn btn-secondary">Manage Permissions</a>
            <a href="<?php echo BASE_URL; ?>/admin/seed_all_modules_permissions.php" class="btn btn-primary">Seed All Permissions</a>
            <a href="<?php echo BASE_URL; ?>/admin/users.php" class="btn btn-secondary">Manage Users</a>
            <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn btn-secondary">Back to Settings</a>
        </div>
    </div>
    
    <!-- Statistics Cards -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-top: 20px;">
        <div style="padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px; color: white;">
            <div style="font-size: 32px; font-weight: bold;"><?php echo number_format($totalRoles); ?></div>
            <div style="font-size: 14px; opacity: 0.9;">Total Roles</div>
        </div>
        
        <div style="padding: 20px; background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); border-radius: 8px; color: white;">
            <div style="font-size: 32px; font-weight: bold;"><?php echo number_format($customRoles); ?></div>
            <div style="font-size: 14px; opacity: 0.9;">Custom Roles</div>
        </div>
        
        <div style="padding: 20px; background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); border-radius: 8px; color: white;">
            <div style="font-size: 32px; font-weight: bold;"><?php echo number_format($totalPermissions); ?></div>
            <div style="font-size: 14px; opacity: 0.9;">Total Permissions</div>
        </div>
        
        <div style="padding: 20px; background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); border-radius: 8px; color: white;">
            <div style="font-size: 32px; font-weight: bold;"><?php echo number_format($totalUsers); ?></div>
            <div style="font-size: 14px; opacity: 0.9;">Active Users</div>
        </div>
    </div>
    
    <!-- Quick Actions -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Quick Actions</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
            <a href="<?php echo BASE_URL; ?>/admin/roles_create.php" style="padding: 20px; background: #f8fafc; border: 2px dashed #cbd5e1; border-radius: 8px; text-decoration: none; color: inherit; display: block; text-align: center; transition: all 0.3s;">
                <div style="font-size: 32px; margin-bottom: 10px;">➕</div>
                <div style="font-weight: 600; color: var(--primary-color);">Create New Role</div>
                <div style="font-size: 12px; color: var(--text-secondary); margin-top: 5px;">Create custom role with specific permissions</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/admin/permissions.php" style="padding: 20px; background: #f8fafc; border: 2px dashed #cbd5e1; border-radius: 8px; text-decoration: none; color: inherit; display: block; text-align: center; transition: all 0.3s;">
                <div style="font-size: 32px; margin-bottom: 10px;">🔐</div>
                <div style="font-weight: 600; color: var(--primary-color);">Manage Permissions</div>
                <div style="font-size: 12px; color: var(--text-secondary); margin-top: 5px;">Create and manage system permissions</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/admin/users.php" style="padding: 20px; background: #f8fafc; border: 2px dashed #cbd5e1; border-radius: 8px; text-decoration: none; color: inherit; display: block; text-align: center; transition: all 0.3s;">
                <div style="font-size: 32px; margin-bottom: 10px;">👥</div>
                <div style="font-weight: 600; color: var(--primary-color);">Assign Roles to Users</div>
                <div style="font-size: 12px; color: var(--text-secondary); margin-top: 5px;">Assign roles to users and employees</div>
            </a>
            
            <a href="<?php echo BASE_URL; ?>/modules/employee/assign_role.php" style="padding: 20px; background: #f8fafc; border: 2px dashed #cbd5e1; border-radius: 8px; text-decoration: none; color: inherit; display: block; text-align: center; transition: all 0.3s;">
                <div style="font-size: 32px; margin-bottom: 10px;">👤</div>
                <div style="font-weight: 600; color: var(--primary-color);">Assign Role to Employee</div>
                <div style="font-size: 12px; color: var(--text-secondary); margin-top: 5px;">Assign roles to employee records</div>
            </a>
        </div>
    </div>
    
    <!-- Users by Role -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Users by Role</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px;">
            <?php foreach ($usersByRole as $role): ?>
            <div style="padding: 15px; background: #f8fafc; border-radius: 8px; border-left: 4px solid var(--primary-color);">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <div style="font-weight: 600; color: var(--text-primary);">
                            <?php echo htmlspecialchars($role['role_name']); ?>
                        </div>
                        <div style="font-size: 12px; color: var(--text-secondary); margin-top: 5px;">
                            <?php echo htmlspecialchars($role['role_code']); ?>
                        </div>
                    </div>
                    <div style="font-size: 24px; font-weight: bold; color: var(--primary-color);">
                        <?php echo number_format($role['user_count']); ?>
                    </div>
                </div>
                <div style="margin-top: 10px;">
                    <a href="<?php echo BASE_URL; ?>/admin/users.php?role_id=<?php echo $role['role_id'] ?? ''; ?>" 
                       class="btn btn-sm btn-secondary">View Users</a>
                    <a href="<?php echo BASE_URL; ?>/admin/roles_view.php?id=<?php echo $role['role_id'] ?? ''; ?>" 
                       class="btn btn-sm btn-primary">View Permissions</a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <!-- Recent Roles -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Recent Roles</h3>
        <?php if (count($recentRoles) > 0): ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Role Code</th>
                    <th>Role Name</th>
                    <th>Type</th>
                    <th>Users</th>
                    <th>Permissions</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recentRoles as $role): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($role['role_code']); ?></strong></td>
                    <td><?php echo htmlspecialchars($role['role_name']); ?></td>
                    <td>
                        <span class="status-badge" style="background: <?php echo $role['is_system_role'] ? '#dbeafe' : '#f3e8ff'; ?>; color: <?php echo $role['is_system_role'] ? '#1e40af' : '#6b21a8'; ?>;">
                            <?php echo $role['is_system_role'] ? 'System' : 'Custom'; ?>
                        </span>
                    </td>
                    <td><?php echo number_format($role['user_count']); ?></td>
                    <td><?php echo number_format($role['permission_count']); ?></td>
                    <td class="table-actions-cell">
                        <a href="<?php echo BASE_URL; ?>/admin/roles_view.php?id=<?php echo $role['role_id']; ?>" 
                           class="btn btn-sm btn-primary">View</a>
                        <?php if (!$role['is_system_role']): ?>
                        <a href="<?php echo BASE_URL; ?>/admin/roles_edit_detail.php?id=<?php echo $role['role_id']; ?>" 
                           class="btn btn-sm btn-secondary">Edit</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
        <div class="table-empty">
            <div class="table-empty-icon">👥</div>
            <div class="table-empty-message">No roles found</div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Permissions by Module -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Permissions by Module</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
            <?php foreach ($permissionsByModule as $module): ?>
            <div style="padding: 15px; background: #f8fafc; border-radius: 8px; text-align: center;">
                <div style="font-size: 24px; font-weight: bold; color: var(--primary-color);">
                    <?php echo number_format($module['count']); ?>
                </div>
                <div style="font-size: 14px; color: var(--text-secondary); margin-top: 5px;">
                    <?php echo htmlspecialchars($module['permission_module']); ?> Module
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<style>
a[style*="border: 2px dashed"]:hover {
    background: #e2e8f0 !important;
    border-color: var(--primary-color) !important;
    transform: translateY(-2px);
}
</style>

<?php include __DIR__ . '/../includes/footer.php'; ?>

