<?php
/**
 * Enterprise HRM ERP System - Role Editor
 * Select role to edit
 */

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

// Check if user is Super Admin - with better error handling
startSession();

// Force refresh role_code from database
$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());
    }
}

// Check if Super Admin (case-insensitive)
if (strtolower($roleCode) !== 'super_admin') {
    redirect(BASE_URL . '/dashboard.php', 'Only Super Admin can edit roles. Your role: ' . ($roleCode ?: 'Unknown'), 'error');
}

$pageTitle = 'Role Editor';
$currentModule = 'settings';

// Get all roles
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT r.*, COUNT(DISTINCT u.user_id) as user_count
        FROM roles r
        LEFT JOIN users u ON r.role_id = u.role_id
        GROUP BY r.role_id
        ORDER BY r.is_system_role DESC, r.role_name
    ");
    $stmt->execute();
    $roles = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading roles: " . $e->getMessage());
    $roles = [];
}

// If role ID is provided, redirect to edit that role
$roleId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($roleId > 0) {
    // Check if role exists
    $roleFound = false;
    foreach ($roles as $role) {
        if ($role['role_id'] == $roleId) {
            $roleFound = true;
            break;
        }
    }
    
    if ($roleFound) {
        // Redirect to detail page
        redirect(BASE_URL . '/admin/roles_edit_detail.php?id=' . $roleId);
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Role Editor</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn btn-secondary">Back to Settings</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Back to Roles</a>
        </div>
    </div>
    
    <?php 
    // Get flash messages
    $success = getFlashMessage('success');
    $error = getFlashMessage('error');
    ?>
    
    <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        <?php echo htmlspecialchars($success); ?>
    </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <?php echo htmlspecialchars($error); ?>
    </div>
    <?php endif; ?>
    
    <div style="margin-top: 20px;">
        <p style="color: var(--text-secondary); margin-bottom: 20px;">
            Select a role to edit its details and permissions.
        </p>
        
        <?php if (empty($roles)): ?>
        <div class="table-empty">
            <div class="table-empty-icon">👥</div>
            <div class="table-empty-message">No roles found</div>
        </div>
        <?php else: ?>
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
            <?php foreach ($roles as $role): ?>
            <div class="card" style="padding: 20px; cursor: pointer; transition: transform 0.2s;" 
                 onmouseover="this.style.transform='scale(1.02)'" 
                 onmouseout="this.style.transform='scale(1)'"
                 onclick="window.location.href='<?php echo BASE_URL; ?>/admin/roles_edit_detail.php?id=<?php echo $role['role_id']; ?>'">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div>
                        <h3 style="margin-bottom: 5px;"><?php echo htmlspecialchars($role['role_name']); ?></h3>
                        <p style="color: var(--text-secondary); font-size: 14px; margin: 0;">
                            <?php echo htmlspecialchars($role['role_code']); ?>
                        </p>
                        <p style="color: var(--text-secondary); font-size: 12px; margin-top: 5px;">
                            <?php echo number_format($role['user_count']); ?> user(s)
                        </p>
                    </div>
                    <div>
                        <span class="status-badge status-<?php echo $role['is_system_role'] ? 'active' : 'inactive'; ?>">
                            <?php echo $role['is_system_role'] ? 'System' : 'Custom'; ?>
                        </span>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

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