<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();

$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
$recoveryReturn = $method === 'GET' && (string)($_GET['return_primary'] ?? '') === '1';
if ($method !== 'POST' && !$recoveryReturn) {
    header('Location: dashboard.php');
    exit;
}

if ($method === 'POST') {
    verify_csrf();
}

$actual = signed_in_primary_role();
$before = active_role();
$requestedPrimary = $method === 'POST' && trim((string)($_POST['task_role'] ?? '')) === 'super_admin';
$returnPrimary = $recoveryReturn || (string)($_POST['return_primary'] ?? '') === '1' || $requestedPrimary;

/*
 * A Superuser task view is only a workspace filter. It must never be able to
 * strand the signed-in owner behind Dentist, Assistant, Cashier, or another
 * focused view. Returning to the primary Superuser identity is therefore an
 * unconditional recovery action: active clinical/cashier UI context is cleared,
 * but the underlying encounter, drawer, and records remain unchanged.
 */
if ($returnPrimary && $actual === 'super_admin') {
    // This normally exits inside require_login() before schema/MFA/Task View
    // gates. Keep the explicit call as a defensive fallback for alternate
    // routing or older front-controller behavior.
    if (function_exists('dental_complete_superuser_primary_return')) {
        dental_complete_superuser_primary_return();
    }
    unset($_SESSION['task_role']);
    $clearedContext = function_exists('dental_task_context_clear_for_switch')
        ? dental_task_context_clear_for_switch($before, $actual)
        : [];

    dental_record_role_switch($actual);

    if ($before !== $actual && !app_demo_read_only()) {
        try {
            audit('active_role_returned_to_superuser', 'user', (int)(current_user()['id'] ?? 0), [
                'actual_role' => $actual,
                'from_role' => $before,
                'to_role' => $actual,
                'recovery_get' => $recoveryReturn,
                'workspace_context_cleared' => true,
                'cleared_context_keys' => $clearedContext,
            ]);
        } catch (Throwable $exception) {
            error_log('DentalCare Superuser return audit deferred: ' . $exception->getMessage());
        }
    }

    flash('success', 'Returned to the signed-in Superuser workspace.');
    header('Location: ' . (function_exists('dental_safety_role_landing_url') ? dental_safety_role_landing_url($actual) : 'dashboard.php'));
    exit;
}

if ($method !== 'POST') {
    header('Location: dashboard.php');
    exit;
}

$allowed = switchable_task_roles($actual);
if (!$allowed) {
    unset($_SESSION['task_role']);
    flash('warning', 'No additional active role is assigned to this account. DentalCare returned you to your primary role.');
    header('Location: dashboard.php');
    exit;
}

$requested = trim((string)($_POST['task_role'] ?? ''));
$after = ($returnPrimary || $requested === '' || $requested === $actual) ? $actual : $requested;

if (!array_key_exists($after, $allowed)) {
    flash('error', 'That role is not assigned, has expired, or is not compatible with this account.');
    header('Location: dashboard.php');
    exit;
}

$blockers = active_role_switch_blockers($after);
if ($blockers) {
    flash('warning', implode(' ', $blockers));
    header('Location: dashboard.php');
    exit;
}

if ($after === $actual) {
    unset($_SESSION['task_role']);
} else {
    $_SESSION['task_role'] = $after;
}

$clearedContext = function_exists('dental_task_context_clear_for_switch')
    ? dental_task_context_clear_for_switch($before, $after)
    : [];

dental_record_role_switch($after);

if ($before !== $after && !app_demo_read_only()) {
    audit('active_role_switched', 'user', (int)(current_user()['id'] ?? 0), [
        'actual_role' => $actual,
        'from_role' => $before,
        'to_role' => $after,
        'role_mode' => active_role_mode($after),
        'cleared_context_keys' => $clearedContext,
    ]);
}

$profile = role_profile($after);
flash('success', 'Task View: ' . (string)$profile['name'] . '. Patient and task context were cleared for this workspace.');
header('Location: ' . (function_exists('dental_safety_role_landing_url') ? dental_safety_role_landing_url($after) : 'dashboard.php'));
exit;
