<?php
/**
 * Enterprise HRM ERP System - Create Custom Role
 */

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 create custom roles. Your role: ' . ($roleCode ?: 'Unknown'), 'error');
}

$pageTitle = 'Create Custom Role';
$currentModule = 'settings';

$errors = [];
$formData = [];

// Get all permissions
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT permission_id, permission_code, permission_name, permission_module
        FROM permissions
        ORDER BY permission_module, permission_name
    ");
    $stmt->execute();
    $allPermissions = $stmt->fetchAll();
    
    // Group by module
    $permissionsByModule = [];
    foreach ($allPermissions as $perm) {
        $module = $perm['permission_module'];
        if (!isset($permissionsByModule[$module])) {
            $permissionsByModule[$module] = [];
        }
        $permissionsByModule[$module][] = $perm;
    }
    
} catch (Exception $e) {
    error_log("Error loading permissions: " . $e->getMessage());
    $permissionsByModule = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'role_code' => sanitize($_POST['role_code'] ?? ''),
        'role_name' => sanitize($_POST['role_name'] ?? ''),
        'role_description' => sanitize($_POST['role_description'] ?? ''),
        'permissions' => $_POST['permissions'] ?? [],
    ];
    
    // Validation
    if (empty($formData['role_code'])) {
        $errors[] = 'Role code is required.';
    } elseif (!preg_match('/^[a-z0-9_]+$/', $formData['role_code'])) {
        $errors[] = 'Role code can only contain lowercase letters, numbers, and underscores.';
    }
    
    if (empty($formData['role_name'])) {
        $errors[] = 'Role name is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if role code exists
            $stmt = $db->prepare("SELECT role_id FROM roles WHERE role_code = ?");
            $stmt->execute([$formData['role_code']]);
            if ($stmt->fetch()) {
                $errors[] = 'Role code already exists.';
                $db->rollBack();
            } else {
                // Insert role
                $stmt = $db->prepare("
                    INSERT INTO roles (role_code, role_name, role_description, is_system_role)
                    VALUES (?, ?, ?, 0)
                ");
                $stmt->execute([
                    $formData['role_code'],
                    $formData['role_name'],
                    $formData['role_description']
                ]);
                
                $roleId = $db->lastInsertId();
                
                // Assign permissions
                if (!empty($formData['permissions'])) {
                    $stmt = $db->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
                    foreach ($formData['permissions'] as $permissionId) {
                        $stmt->execute([$roleId, (int)$permissionId]);
                    }
                }
                
                $db->commit();
                
                logAudit('CREATE', 'roles', $roleId);
                
                redirect(BASE_URL . '/admin/roles.php', 'Custom role created successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating role: " . $e->getMessage());
            $errors[] = 'An error occurred while creating role. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Create Custom Role</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 if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="role_code">Role Code *</label>
                <input type="text" id="role_code" name="role_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['role_code'] ?? ''); ?>"
                       placeholder="e.g., custom_manager, department_head"
                       pattern="[a-z0-9_]+" title="Only lowercase letters, numbers, and underscores">
                <small style="color: var(--text-secondary);">Only lowercase letters, numbers, and underscores</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="role_name">Role Name *</label>
                <input type="text" id="role_name" name="role_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['role_name'] ?? ''); ?>"
                       placeholder="e.g., Custom Manager">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="role_description">Description</label>
                <textarea id="role_description" name="role_description" class="form-control" rows="2"
                          placeholder="Enter role description..."><?php echo htmlspecialchars($formData['role_description'] ?? ''); ?></textarea>
            </div>
        </div>
        
        <!-- Permissions Selection -->
        <div style="margin-top: 30px;">
            <h3 style="margin-bottom: 15px;">Assign Permissions</h3>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
                <?php foreach ($permissionsByModule as $module => $permissions): ?>
                <div style="padding: 15px; background: #f9fafb; border-radius: 8px;">
                    <h4 style="margin-bottom: 10px; text-transform: uppercase; color: var(--primary-color);">
                        <?php echo htmlspecialchars($module); ?>
                    </h4>
                    <?php foreach ($permissions as $perm): ?>
                    <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px; cursor: pointer;">
                        <input type="checkbox" name="permissions[]" value="<?php echo $perm['permission_id']; ?>"
                               <?php echo in_array($perm['permission_id'], $formData['permissions'] ?? []) ? 'checked' : ''; ?>>
                        <span><?php echo htmlspecialchars($perm['permission_name']); ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div style="margin-top: 15px;">
                <button type="button" onclick="selectAllPermissions()" class="btn btn-sm btn-secondary">Select All</button>
                <button type="button" onclick="deselectAllPermissions()" class="btn btn-sm btn-secondary">Deselect All</button>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create Role</button>
        </div>
    </form>
</div>

<script>
function selectAllPermissions() {
    document.querySelectorAll('input[name="permissions[]"]').forEach(cb => cb.checked = true);
}

function deselectAllPermissions() {
    document.querySelectorAll('input[name="permissions[]"]').forEach(cb => cb.checked = false);
}
</script>

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