<?php

/**
 * @var array $tenants
 * @var array $roles
 * @var array $departments
 * @var array $values
 * @var array $settings
 * @var bool $canUpdateSettings
 */

use MintyPHP\Session;
use MintyPHP\Service\Branding\BrandingServicesFactory;

$values = $values ?? [];
$settings = $settings ?? [];
$defaultTenantId = (int) ($values['default_tenant_id'] ?? 0);
$defaultRoleId = (int) ($values['default_role_id'] ?? 0);
$defaultDepartmentId = (int) ($values['default_department_id'] ?? 0);
$appTitle = (string) ($values['app_title'] ?? '');
$appLocale = (string) ($values['app_locale'] ?? '');
$appTheme = (string) ($values['app_theme'] ?? '');
$appThemeUser = !empty($values['app_theme_user']);
$appRegistration = !empty($values['app_registration']);
$apiTokenDefaultTtlDays = (int) ($values['api_token_default_ttl_days'] ?? 90);
$apiTokenMaxTtlDays = (int) ($values['api_token_max_ttl_days'] ?? 365);
$userInactivityDeactivateDays = (int) ($values['user_inactivity_deactivate_days'] ?? 180);
$userInactivityDeleteDays = (int) ($values['user_inactivity_delete_days'] ?? 365);
$sessionIdleTimeoutMinutes = (int) ($values['session_idle_timeout_minutes'] ?? 30);
$sessionAbsoluteTimeoutHours = (int) ($values['session_absolute_timeout_hours'] ?? 8);
$microsoftAutoRememberDefault = !empty($values['microsoft_auto_remember_default']);
$rememberTokenLifetimeDays = (int) ($values['remember_token_lifetime_days'] ?? 30);
$apiCorsAllowedOrigins = (string) ($values['api_cors_allowed_origins'] ?? '');
$systemAuditEnabled = !empty($values['system_audit_enabled']);
$systemAuditRetentionDays = (int) ($values['system_audit_retention_days'] ?? 365);
$frontendTelemetryEnabled = !empty($values['frontend_telemetry_enabled']);
$frontendTelemetrySampleRate = (string) ($values['frontend_telemetry_sample_rate'] ?? '0.2');
$frontendTelemetrySampleRateOptions = ['0.1', '0.2', '0.5', '1'];
if (!in_array($frontendTelemetrySampleRate, $frontendTelemetrySampleRateOptions, true)) {
  $frontendTelemetrySampleRate = '0.2';
}
$frontendTelemetryAllowedEvents = $values['frontend_telemetry_allowed_events'] ?? ['warn_once', 'ajax_error'];
if (!is_array($frontendTelemetryAllowedEvents)) {
  $frontendTelemetryAllowedEvents = preg_split('/[\s,]+/', (string) $frontendTelemetryAllowedEvents) ?: [];
}
$frontendTelemetryAllowedEvents = array_values(array_unique(array_filter(array_map(
  static fn($entry): string => strtolower(trim((string) $entry)),
  $frontendTelemetryAllowedEvents
))));
if ($frontendTelemetryAllowedEvents === []) {
  $frontendTelemetryAllowedEvents = ['warn_once', 'ajax_error'];
}
$appPrimaryColor = (string) ($values['app_primary_color'] ?? '');
$microsoftSharedClientId = (string) ($values['microsoft_shared_client_id'] ?? '');
$microsoftAuthority = (string) ($values['microsoft_authority'] ?? '');
$themes = appThemes();
$smtpHost = (string) ($values['smtp_host'] ?? '');
$smtpPort = (string) ($values['smtp_port'] ?? '');
$smtpUser = (string) ($values['smtp_user'] ?? '');
$smtpSecure = (string) ($values['smtp_secure'] ?? '');
$smtpFrom = (string) ($values['smtp_from'] ?? '');
$smtpFromName = (string) ($values['smtp_from_name'] ?? '');
$activeLoginTokens = (int) ($activeLoginTokens ?? 0);
$activeApiTokens = (int) ($activeApiTokens ?? 0);
$defaultTenantDesc = $settings['default_tenant']['description'] ?? 'setting.default_tenant';
$defaultRoleDesc = $settings['default_role']['description'] ?? 'setting.default_role';
$defaultDepartmentDesc = $settings['default_department']['description'] ?? 'setting.default_department';
$appTitleDesc = $settings['app_title']['description'] ?? 'setting.app_title';
$appLocaleDesc = $settings['app_locale']['description'] ?? 'setting.app_locale';
$appThemeDesc = $settings['app_theme']['description'] ?? 'setting.app_theme';
$appThemeUserDesc = $settings['app_theme_user']['description'] ?? 'setting.app_theme_user';
$appRegistrationDesc = $settings['app_registration']['description'] ?? 'setting.app_registration';
$apiTokenDefaultTtlDaysDesc = $settings['api_token_default_ttl_days']['description'] ?? 'setting.api_token_default_ttl_days';
$apiTokenMaxTtlDaysDesc = $settings['api_token_max_ttl_days']['description'] ?? 'setting.api_token_max_ttl_days';
$userInactivityDeactivateDaysDesc = $settings['user_inactivity_deactivate_days']['description'] ?? 'setting.user_inactivity_deactivate_days';
$userInactivityDeleteDaysDesc = $settings['user_inactivity_delete_days']['description'] ?? 'setting.user_inactivity_delete_days';
$sessionIdleTimeoutMinutesDesc = $settings['session_idle_timeout_minutes']['description'] ?? 'setting.session_idle_timeout_minutes';
$sessionAbsoluteTimeoutHoursDesc = $settings['session_absolute_timeout_hours']['description'] ?? 'setting.session_absolute_timeout_hours';
$microsoftAutoRememberDefaultDesc = $settings['microsoft_auto_remember_default']['description'] ?? 'setting.microsoft_auto_remember_default';
$rememberTokenLifetimeDaysDesc = $settings['remember_token_lifetime_days']['description'] ?? 'setting.remember_token_lifetime_days';
$apiCorsAllowedOriginsDesc = $settings['api_cors_allowed_origins']['description'] ?? 'setting.api_cors_allowed_origins';
$systemAuditEnabledDesc = $settings['system_audit_enabled']['description'] ?? 'setting.system_audit_enabled';
$systemAuditRetentionDaysDesc = $settings['system_audit_retention_days']['description'] ?? 'setting.system_audit_retention_days';
$appPrimaryColorDesc = $settings['app_primary_color']['description'] ?? 'setting.app_primary_color';
$microsoftSharedClientIdDesc = $settings['microsoft_shared_client_id']['description'] ?? 'setting.microsoft_shared_client_id';
$microsoftSharedClientSecretDesc = $settings['microsoft_shared_client_secret_enc']['description'] ?? 'setting.microsoft_shared_client_secret_enc';
$microsoftAuthorityDesc = $settings['microsoft_authority']['description'] ?? 'setting.microsoft_authority';
$smtpHostDesc = $settings['smtp_host']['description'] ?? 'setting.smtp_host';
$smtpPortDesc = $settings['smtp_port']['description'] ?? 'setting.smtp_port';
$smtpUserDesc = $settings['smtp_user']['description'] ?? 'setting.smtp_user';
$smtpPasswordDesc = $settings['smtp_password']['description'] ?? 'setting.smtp_password';
$smtpSecureDesc = $settings['smtp_secure']['description'] ?? 'setting.smtp_secure';
$smtpFromDesc = $settings['smtp_from']['description'] ?? 'setting.smtp_from';
$smtpFromNameDesc = $settings['smtp_from_name']['description'] ?? 'setting.smtp_from_name';
$locales = defined('APP_LOCALES') ? APP_LOCALES : [];
$hasLogo = app(\MintyPHP\Service\Branding\BrandingLogoService::class)->hasLogo();
$hasFavicon = app(\MintyPHP\Service\Branding\BrandingFaviconService::class)->hasFavicon();
$canUpdateSettings = (bool) ($canUpdateSettings ?? false);
$isReadOnly = !$canUpdateSettings;
$readonlyAttr = $isReadOnly ? 'readonly' : '';
$disabledAttr = $isReadOnly ? 'disabled' : '';
?>

<div class="app-details-container">
  <section>
    <?php
    $breadcrumbs = [
      ['label' => t('Home'), 'path' => 'admin'],
      ['label' => t('Settings')],
    ];
    require templatePath('partials/app-breadcrumb.phtml');
    $titlebar = [
      'title' => t('Settings'),
      'actions' => $canUpdateSettings ? [
        [
          'type' => 'submit',
          'form' => 'settings-form',
          'class' => 'primary',
          'label' => t('Save'),
          'detailSavePrimary' => true,
          'detailActionKind' => 'save',
        ],
      ] : [],
    ];
    require templatePath('partials/app-details-titlebar.phtml');
    ?>

    <form id="settings-form" method="post" data-details-storage="settings-main-details-v1" data-standard-detail-form="1">
      <input type="hidden" name="settings_submit" value="1">

      <div class="app-tabs" data-tabs data-tabs-param="tab" data-tabs-storage-key="admin-settings-tabs-v1">
        <div class="app-tabs-nav">
          <button type="button" data-tab="master-data" data-tab-default><?php e(t('Master data')); ?></button>
          <button type="button" data-tab="appearance"><?php e(t('Appearance')); ?></button>
          <button type="button" data-tab="security"><?php e(t('Security')); ?></button>
          <button type="button" data-tab="email"><?php e(t('Email')); ?></button>
          <button type="button" data-tab="api"><?php e(t('API')); ?></button>
          <button type="button" data-tab="integrations"><?php e(t('Microsoft SSO')); ?></button>
          <?php if ($canUpdateSettings): ?>
            <button type="button" data-tab="danger"><?php e(t('Danger zone')); ?></button>
          <?php endif; ?>
        </div>

        <div data-tab-panel="master-data">
          <details class="app-details-card" name="settings-master-app-identity" data-details-key="settings-master-app-identity" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('App identity')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($appTitle !== '' ? t('Configured') : t('Default')); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('This setting controls the application name shown across the UI.')); ?></small>
              </blockquote>
              <label class="app-field">
                <span><?php e(t('App title')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></span>
                <input type="text" name="app_title" value="<?php e($appTitle); ?>" placeholder="<?php e(appTitle()); ?>" <?php e($readonlyAttr); ?>>
                <small><?php e(t($appTitleDesc)); ?></small>
                <small class="muted"><?php e(t('Leave empty to use the runtime default title.')); ?></small>
              </label>
            </div>
          </details>

          <details class="app-details-card" name="internationalization" data-details-key="internationalization">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Internationalization')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($appLocale !== '' ? strtoupper($appLocale) : t('Default')); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('This setting controls the default language for users without a personal preference.')); ?></small>
              </blockquote>
              <label class="app-field">
                <span><?php e(t('Default language')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></span>
                <select name="app_locale" <?php e($disabledAttr); ?>>
                  <option value=""><?php e(t('None')); ?></option>
                  <?php foreach ($locales as $locale): ?>
                    <?php
                    $label = strtoupper($locale);
                    if ($locale === 'de') {
                      $label = t('German');
                    } elseif ($locale === 'en') {
                      $label = t('English');
                    }
                    ?>
                    <option value="<?php e($locale); ?>" <?php e($appLocale === $locale ? 'selected' : ''); ?>>
                      <?php e($label); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
                <small><?php e(t($appLocaleDesc)); ?></small>
              </label>
            </div>
          </details>

          <?php $configuredDefaultsCount = (int) ($defaultTenantId > 0) + (int) ($defaultDepartmentId > 0) + (int) ($defaultRoleId > 0); ?>
          <details class="app-details-card" name="user-creation" data-details-key="user-creation">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('User creation rules')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e(sprintf(t('%d defaults configured'), $configuredDefaultsCount)); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('These defaults prefill tenant, department and role when new users are created.')); ?></small>
              </blockquote>
              <div class="grid">
                <label class="app-field">
                  <span><?php e(t('Default tenant')); ?></span>
                  <select name="default_tenant_id" <?php e($disabledAttr); ?>>
                    <option value=""><?php e(t('None')); ?></option>
                    <?php foreach ($tenants ?? [] as $tenant): ?>
                      <?php $tenantId = (int) ($tenant['id'] ?? 0); ?>
                      <?php if ($tenantId > 0): ?>
                        <option value="<?php e((string) $tenantId); ?>" <?php e($tenantId === $defaultTenantId ? 'selected' : ''); ?>>
                          <?php e($tenant['description'] ?? ''); ?>
                        </option>
                      <?php endif; ?>
                    <?php endforeach; ?>
                  </select>
                  <small><?php e(t($defaultTenantDesc)); ?></small>
                </label>
                <label class="app-field">
                  <span><?php e(t('Default department')); ?></span>
                  <select name="default_department_id" <?php e($disabledAttr); ?>>
                    <option value=""><?php e(t('None')); ?></option>
                    <?php foreach ($departments ?? [] as $department): ?>
                      <?php $departmentId = (int) ($department['id'] ?? 0); ?>
                      <?php if ($departmentId > 0): ?>
                        <option value="<?php e((string) $departmentId); ?>" <?php e($departmentId === $defaultDepartmentId ? 'selected' : ''); ?>>
                          <?php e($department['description'] ?? ''); ?>
                        </option>
                      <?php endif; ?>
                    <?php endforeach; ?>
                  </select>
                  <small><?php e(t($defaultDepartmentDesc)); ?></small>
                </label>
              </div>
              <label class="app-field">
                <span><?php e(t('Default role')); ?></span>
                <select name="default_role_id" <?php e($disabledAttr); ?>>
                  <option value=""><?php e(t('None')); ?></option>
                  <?php foreach ($roles ?? [] as $role): ?>
                    <?php $roleId = (int) ($role['id'] ?? 0); ?>
                    <?php if ($roleId > 0): ?>
                      <option value="<?php e((string) $roleId); ?>" <?php e($roleId === $defaultRoleId ? 'selected' : ''); ?>>
                        <?php e($role['description'] ?? ''); ?>
                      </option>
                    <?php endif; ?>
                  <?php endforeach; ?>
                </select>
                <small><?php e(t($defaultRoleDesc)); ?></small>
              </label>
            </div>
          </details>
        </div>

        <div data-tab-panel="appearance">
          <details class="app-details-card" name="settings-appearance-theme" data-details-key="settings-appearance-theme" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Theme policy')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($appTheme !== '' ? t($themes[$appTheme] ?? $appTheme) : t('Default')); ?></span>
                <span class="badge" data-variant="neutral"><?php e($appThemeUser ? t('User override enabled') : t('User override disabled')); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('This setting controls the global default theme and whether users may choose their own theme.')); ?></small>
              </blockquote>
              <label class="app-field">
                <span><?php e(t('Default theme')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></span>
                <select name="app_theme" <?php e($disabledAttr); ?>>
                  <option value=""><?php e(t('None')); ?></option>
                  <?php foreach ($themes as $key => $label): ?>
                    <option value="<?php e($key); ?>" <?php e($appTheme === $key ? 'selected' : ''); ?>>
                      <?php e(t($label)); ?>
                    </option>
                  <?php endforeach; ?>
                </select>
                <small><?php e(t($appThemeDesc)); ?></small>
              </label>
              <fieldset>
                <legend><small><?php e(t($appThemeUserDesc)); ?></small></legend>
                <label class="app-field">
                  <input type="checkbox" role="switch" name="app_theme_user" value="1" <?php e($appThemeUser ? 'checked' : ''); ?> <?php e($disabledAttr); ?>>
                  <span><?php e(t('Allow user theme')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></span>
                </label>
              </fieldset>
              <small class="muted"><?php e(t('Tenants can override color and theme behavior in their appearance settings.')); ?></small>
            </div>
          </details>

          <details class="app-details-card" name="settings-appearance-branding" data-details-key="settings-appearance-branding">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Brand color')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($appPrimaryColor !== '' ? strtoupper($appPrimaryColor) : t('Default')); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('This setting controls the primary UI accent color for the default app theme.')); ?></small>
              </blockquote>
              <fieldset>
                <legend><small><?php e(t('Primary color')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></small></legend>
                <label class="app-field">
                  <input type="color" name="app_primary_color"
                    value="<?php e($appPrimaryColor !== '' ? $appPrimaryColor : '#2fa4a4'); ?>" <?php e($disabledAttr); ?>>
                  <div>
                    <div><?php e(t('Choose color')); ?></div>
                  </div>
                </label>
                <small class="muted"><?php e(t($appPrimaryColorDesc)); ?></small>
              </fieldset>
            </div>
          </details>
        </div>

        <div data-tab-panel="security">
          <details class="app-details-card" name="settings-security-registration" data-details-key="settings-security-registration">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Allow registration')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($appRegistration ? t('Enabled') : t('Disabled')); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('Registration controls whether new users can create an account.')); ?></small>
              </blockquote>
              <fieldset>
                <legend>
                  <small>
                    <?php e(t($appRegistrationDesc)); ?>
                  </small>
                </legend>
                <label class="app-field">
                  <input type="checkbox" name="app_registration" value="1" <?php e($appRegistration ? 'checked' : ''); ?>
                    <?php e($disabledAttr); ?>>
                  <span><?php e(t('Allow registration')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></span>
                </label>
              </fieldset>
            </div>
          </details>

          <details class="app-details-card" name="settings-security-session" data-details-key="settings-security-session" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Session policy')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e((string) $sessionIdleTimeoutMinutes); ?></span>
                <span class="badge" data-variant="neutral"><?php e((string) $sessionAbsoluteTimeoutHours); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">

              <blockquote data-variant="info">
                <small>
                  <?php e(t('Session limits define how long logged-in users stay signed in.')); ?>
                </small>
              </blockquote>
              <div class="grid">
                <label class="app-field">
                  <span><?php e(t('Session idle timeout (minutes)')); ?></span>
                  <input type="number" name="session_idle_timeout_minutes"
                    value="<?php e((string) $sessionIdleTimeoutMinutes); ?>" min="5" max="1440" step="1"
                    <?php e($readonlyAttr); ?>>
                  <small><?php e(t($sessionIdleTimeoutMinutesDesc)); ?></small>
                  <small class="muted"><?php e(t('Allowed range: 5-1440 minutes (default: 30)')); ?></small>
                </label>
                <label class="app-field">
                  <span><?php e(t('Session absolute timeout (hours)')); ?></span>
                  <input type="number" name="session_absolute_timeout_hours"
                    value="<?php e((string) $sessionAbsoluteTimeoutHours); ?>" min="1" max="72" step="1"
                    <?php e($readonlyAttr); ?>>
                  <small><?php e(t($sessionAbsoluteTimeoutHoursDesc)); ?></small>
                  <small class="muted"><?php e(t('Allowed range: 1-72 hours (default: 8)')); ?></small>
                </label>
              </div>
            </div>
          </details>

          <details class="app-details-card" name="settings-security-login-persistence" data-details-key="settings-security-login-persistence">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Login persistence')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e((string) $rememberTokenLifetimeDays); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('Controls remember-me token lifetime and Microsoft auto-remember behavior.')); ?></small>
              </blockquote>
              <div class="grid">
                <label class="app-field">
                  <span><?php e(t('Remember token lifetime (days)')); ?></span>
                  <input type="number" name="remember_token_lifetime_days"
                    value="<?php e((string) $rememberTokenLifetimeDays); ?>" min="1" max="365" step="1"
                    <?php e($readonlyAttr); ?>>
                  <small><?php e(t($rememberTokenLifetimeDaysDesc)); ?></small>
                  <small class="muted"><?php e(t('Allowed range: 1-365 days (default: 30)')); ?></small>
                </label>
                <fieldset>
                  <legend>
                    <small><?php e(t($microsoftAutoRememberDefaultDesc)); ?></small>
                  </legend>
                  <label class="app-field">
                    <input type="checkbox" name="microsoft_auto_remember_default" value="1"
                      <?php e($microsoftAutoRememberDefault ? 'checked' : ''); ?>
                      <?php e($disabledAttr); ?>>
                    <span><?php e(t('Microsoft Auto-Remember default')); ?></span>
                  </label>
                  <small class="muted"><?php e(t('When enabled, successful Microsoft logins automatically persist a remember-me token (unless overridden per tenant).')); ?></small>
                </fieldset>
              </div>
            </div>
          </details>
          <details class="app-details-card" name="settings-security-user-lifecycle" data-details-key="settings-security-user-lifecycle">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('User lifecycle policy')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e((string) $userInactivityDeactivateDays); ?></span>
                <span class="badge" data-variant="neutral"><?php e((string) $userInactivityDeleteDays); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('User lifecycle defines when inactive users are deactivated or deleted.')); ?></small>
              </blockquote>
              <div class="grid">
                <label class="app-field">
                  <span><?php e(t('Deactivate users after inactivity (days)')); ?></span>
                  <input type="number" name="user_inactivity_deactivate_days"
                    value="<?php e((string) $userInactivityDeactivateDays); ?>" min="0" max="3650" step="1"
                    <?php e($readonlyAttr); ?>>
                  <small><?php e(t($userInactivityDeactivateDaysDesc)); ?> - <?php e(t('0 disables this rule')); ?></small>
                </label>
                <label class="app-field">
                  <span><?php e(t('Delete inactive users after (days)')); ?></span>
                  <input type="number" name="user_inactivity_delete_days"
                    value="<?php e((string) $userInactivityDeleteDays); ?>" min="0" max="3650" step="1"
                    <?php e($readonlyAttr); ?>>
                  <small><?php e(t($userInactivityDeleteDaysDesc)); ?> - <?php e(t('0 disables this rule')); ?></small>
                </label>
              </div>

              <?php if ($canUpdateSettings): ?>
                <button type="submit" class="danger" formnovalidate
                  formaction="admin/settings/run-user-lifecycle"
                  formmethod="post"
                  data-detail-confirm-message="<?php e(t('Run user lifecycle now?')); ?>"
                  data-detail-action-kind="danger">
                  <?php e(t('Run user lifecycle now')); ?>
                </button>
              <?php endif; ?>

            </div>
          </details>
          <details class="app-details-card" name="settings-security-system-audit" data-details-key="settings-security-system-audit">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('System audit')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($systemAuditEnabled ? t('Enabled') : t('Disabled')); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('System audit controls whether security events are logged and how long they are kept.')); ?></small>
              </blockquote>
              <label class="app-field">
                <input type="checkbox" name="system_audit_enabled" value="1" <?php e($systemAuditEnabled ? 'checked' : ''); ?> <?php e($disabledAttr); ?>>
                <span><?php e(t('Enable system audit log')); ?></span>
              </label>
              <hr>
              <label class="app-field">
                <span><?php e(t('Retention (days)')); ?></span>
                <input
                  type="number"
                  name="system_audit_retention_days"
                  value="<?php e((string) $systemAuditRetentionDays); ?>"
                  min="30"
                  max="1095"
                  step="1"
                  <?php e($readonlyAttr); ?>>
                <small><?php e(t($systemAuditRetentionDaysDesc)); ?></small>
              </label>
            </div>
          </details>

          <details class="app-details-card" name="settings-telemetry-core" data-details-key="settings-telemetry-core" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Frontend telemetry')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($frontendTelemetryEnabled ? t('Enabled') : t('Disabled')); ?></span>
                <span class="badge" data-variant="neutral"><?php e($frontendTelemetrySampleRate); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('Telemetry helps detect recurring UI issues and failed requests in production.')); ?></small>
              </blockquote>
              <fieldset>
                <legend><small><?php e(t('Frontend telemetry')); ?></small></legend>
                <label class="app-field">
                  <input
                    type="checkbox"
                    role="switch"
                    name="frontend_telemetry_enabled"
                    value="1"
                    data-telemetry-enabled-toggle
                    <?php e($frontendTelemetryEnabled ? 'checked' : ''); ?>
                    <?php e($disabledAttr); ?>>
                  <span><?php e(t('Enable frontend telemetry')); ?></span>
                </label>
              </fieldset>
              <fieldset data-telemetry-sampling-fieldset <?php e($frontendTelemetryEnabled ? '' : 'hidden'); ?>>
                <legend><small><?php e(t('Sampling rate')); ?></small></legend>
                <label class="app-field" data-telemetry-sampling-row>
                  <span><?php e(t('Sampling rate')); ?></span>
                  <select name="frontend_telemetry_sample_rate" data-telemetry-sampling-select <?php e($disabledAttr); ?>>
                    <option value="0.1" <?php e($frontendTelemetrySampleRate === '0.1' ? 'selected' : ''); ?>>10%</option>
                    <option value="0.2" <?php e($frontendTelemetrySampleRate === '0.2' ? 'selected' : ''); ?>>20%</option>
                    <option value="0.5" <?php e($frontendTelemetrySampleRate === '0.5' ? 'selected' : ''); ?>>50%</option>
                    <option value="1" <?php e($frontendTelemetrySampleRate === '1' ? 'selected' : ''); ?>>100%</option>
                  </select>
                  <small><?php e(t('The percentage of users who will have telemetry enabled.')); ?></small>
                </label>
              </fieldset>
            </div>
          </details>
          <details class="app-details-card" name="telemetry-advanced" data-details-key="telemetry-advanced">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Advanced telemetry options')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e(sprintf(t('%d events enabled'), count($frontendTelemetryAllowedEvents))); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('Limit which event types are collected to match your privacy and operations requirements.')); ?></small>
              </blockquote>
              <fieldset>
                <legend><small><?php e(t('Allowed telemetry events')); ?></small></legend>
                <label class="app-field">
                  <input type="checkbox" name="frontend_telemetry_allowed_events[]" value="warn_once" <?php e(in_array('warn_once', $frontendTelemetryAllowedEvents, true) ? 'checked' : ''); ?> <?php e($disabledAttr); ?>>
                  <span><?php e(t('warnOnce warnings')); ?></span>
                </label>
                <label class="app-field">
                  <input type="checkbox" name="frontend_telemetry_allowed_events[]" value="ajax_error" <?php e(in_array('ajax_error', $frontendTelemetryAllowedEvents, true) ? 'checked' : ''); ?> <?php e($disabledAttr); ?>>
                  <span><?php e(t('AJAX errors')); ?></span>
                </label>
              </fieldset>
            </div>
          </details>
        </div>

        <div data-tab-panel="email">
          <div class="grid">
            <label class="app-field">
              <span><?php e(t('SMTP host')); ?></span>
              <input type="text" name="smtp_host" value="<?php e($smtpHost); ?>" <?php e($readonlyAttr); ?>>
              <small><?php e(t($smtpHostDesc)); ?></small>
            </label>
            <label class="app-field">
              <span><?php e(t('SMTP port')); ?></span>
              <input type="number" name="smtp_port" value="<?php e($smtpPort); ?>" min="1" max="65535" <?php e($readonlyAttr); ?>>
              <small><?php e(t($smtpPortDesc)); ?></small>
            </label>
          </div>
          <div class="grid">
            <label class="app-field">
              <span><?php e(t('SMTP user')); ?></span>
              <input type="text" name="smtp_user" value="<?php e($smtpUser); ?>" autocomplete="username" <?php e($readonlyAttr); ?>>
              <small><?php e(t($smtpUserDesc)); ?></small>
            </label>
            <label class="app-field">
              <span><?php e(t('SMTP password')); ?></span>
              <input type="password" name="smtp_password" value="" autocomplete="new-password" <?php e($readonlyAttr); ?>>
              <small><?php e(t($smtpPasswordDesc)); ?></small>
            </label>
          </div>
          <div class="grid">
            <label class="app-field">
              <span><?php e(t('SMTP security')); ?></span>
              <select name="smtp_secure" <?php e($disabledAttr); ?>>
                <option value=""><?php e(t('None')); ?></option>
                <option value="tls" <?php e($smtpSecure === 'tls' ? 'selected' : ''); ?>>TLS</option>
                <option value="ssl" <?php e($smtpSecure === 'ssl' ? 'selected' : ''); ?>>SSL</option>
              </select>
              <small><?php e(t($smtpSecureDesc)); ?></small>
            </label>
            <label class="app-field">
              <span><?php e(t('SMTP from address')); ?></span>
              <input type="email" name="smtp_from" value="<?php e($smtpFrom); ?>" <?php e($readonlyAttr); ?>>
              <small><?php e(t($smtpFromDesc)); ?></small>
            </label>
          </div>
          <label class="app-field">
            <span><?php e(t('SMTP from name')); ?></span>
            <input type="text" name="smtp_from_name" value="<?php e($smtpFromName); ?>" <?php e($readonlyAttr); ?>>
            <small><?php e(t($smtpFromNameDesc)); ?></small>
          </label>
        </div>

        <div data-tab-panel="api">
          <details class="app-details-card" name="settings-api-token-policy" data-details-key="settings-api-token-policy" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Token lifetime policy')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral">
                  <?php e((string) $apiTokenDefaultTtlDays); ?> / <?php e((string) $apiTokenMaxTtlDays); ?> <?php e(t('days')); ?>
                </span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('These limits define default and maximum lifetimes for newly issued API tokens.')); ?></small>
              </blockquote>
              <div class="grid">
                <label class="app-field">
                  <span><?php e(t('API token default lifetime (days)')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></span>
                  <input type="number" name="api_token_default_ttl_days" value="<?php e((string) $apiTokenDefaultTtlDays); ?>"
                    min="1" max="3650" step="1" <?php e($readonlyAttr); ?>>
                  <small><?php e(t($apiTokenDefaultTtlDaysDesc)); ?></small>
                </label>
                <label class="app-field">
                  <span><?php e(t('API token maximum lifetime (days)')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></span>
                  <input type="number" name="api_token_max_ttl_days" value="<?php e((string) $apiTokenMaxTtlDays); ?>"
                    min="1" max="3650" step="1" <?php e($readonlyAttr); ?>>
                  <small><?php e(t($apiTokenMaxTtlDaysDesc)); ?></small>
                </label>
              </div>
            </div>
          </details>

          <?php $apiCorsOriginsCount = count(array_values(array_filter(array_map('trim', preg_split('/\R+/', $apiCorsAllowedOrigins) ?: [])))); ?>
          <details class="app-details-card" name="settings-api-cors" data-details-key="settings-api-cors">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('CORS allowlist')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e(sprintf(t('%d origins configured'), $apiCorsOriginsCount)); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('Define which origins may call your API from browsers. Use one origin per line.')); ?></small>
              </blockquote>
              <label class="app-field">
                <span><?php e(t('Allowed CORS origins')); ?> <span class="badge" data-variant="info"><?php e(t('Cached')); ?></span></span>
                <textarea name="api_cors_allowed_origins" rows="4" placeholder="https://app.example.com&#10;https://admin.example.com" <?php e($readonlyAttr); ?>><?php e($apiCorsAllowedOrigins); ?></textarea>
                <small><?php e(t($apiCorsAllowedOriginsDesc)); ?></small>
              </label>
              <small class="muted"><?php e(t('One origin per line, e.g. https://app.example.com')); ?></small>
            </div>
          </details>

          <?php if ($canUpdateSettings): ?>
            <details class="app-details-card" name="settings-api-tokens" data-details-key="settings-api-tokens">
              <summary>
                <span class="app-details-card-summary-title"><?php e(t('Token operations')); ?></span>
                <span class="app-details-card-summary-meta">
                  <span class="badge" data-variant="neutral"><?php e(sprintf(t('%d active API tokens'), $activeApiTokens)); ?></span>
                </span>
              </summary>
              <div class="app-details-card-container">
                <blockquote data-variant="warning">
                  <small><?php e(t('This action revokes all active API tokens immediately across all users.')); ?></small>
                </blockquote>
                <button type="submit" class="danger" formnovalidate
                  formaction="admin/settings/revoke-api-tokens"
                  formmethod="post"
                  data-detail-confirm-message="<?php e(t('Revoke all API tokens?')); ?>"
                  data-detail-action-kind="danger">
                  <?php e(t('Revoke all API tokens')); ?>
                </button>
              </div>
            </details>
          <?php endif; ?>
        </div>

        <div data-tab-panel="integrations">
          <details class="app-details-card" name="settings-integrations-microsoft-auth" data-details-key="settings-integrations-microsoft-auth" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Shared Microsoft credentials')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($microsoftSharedClientId !== '' ? t('Configured') : t('Not configured')); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('Shared Microsoft app credentials are used by tenants that enable "Use shared app credentials".')); ?></small>
              </blockquote>
              <label class="app-field">
                <span><?php e(t('Shared client ID')); ?></span>
                <input type="text" name="microsoft_shared_client_id" value="<?php e($microsoftSharedClientId); ?>" <?php e($readonlyAttr); ?>>
                <small><?php e(t($microsoftSharedClientIdDesc)); ?></small>
              </label>
              <label class="app-field">
                <span><?php e(t('Shared client secret')); ?></span>
                <input type="password" name="microsoft_shared_client_secret" value="" autocomplete="new-password" <?php e($readonlyAttr); ?>>
                <small><?php e(t($microsoftSharedClientSecretDesc)); ?></small>
                <small class="muted"><?php e(t('Leave empty to keep the currently stored client secret.')); ?></small>
              </label>
            </div>
          </details>

          <details class="app-details-card" name="settings-integrations-microsoft-authority" data-details-key="settings-integrations-microsoft-authority">
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Authority endpoint')); ?></span>
              <span class="app-details-card-summary-meta">
                <span class="badge" data-variant="neutral"><?php e($microsoftAuthority !== '' ? t('Configured') : t('Not configured')); ?></span>
              </span>
            </summary>
            <div class="app-details-card-container">
              <blockquote data-variant="info">
                <small><?php e(t('The authority URL defines the Microsoft identity tenant endpoint used for sign-in.')); ?></small>
              </blockquote>
              <label class="app-field">
                <span><?php e(t('Authority URL')); ?></span>
                <input type="url" name="microsoft_authority" value="<?php e($microsoftAuthority); ?>" placeholder="https://login.microsoftonline.com/common/v2.0" <?php e($readonlyAttr); ?>>
                <small><?php e(t($microsoftAuthorityDesc)); ?></small>
              </label>
            </div>
          </details>
        </div>

        <?php if ($canUpdateSettings): ?>
          <div data-tab-panel="danger">
            <details class="app-details-card" name="settings-danger-login-tokens" data-details-key="settings-danger-login-tokens" open>
              <summary>
                <span class="app-details-card-summary-title"><?php e(t('Login tokens')); ?></span>
                <span class="app-details-card-summary-meta">
                  <span class="badge" data-variant="neutral"><?php e(sprintf(t('%d active login tokens'), $activeLoginTokens)); ?></span>
                </span>
              </summary>
              <div class="app-details-card-container">
                <blockquote data-variant="warning">
                  <small><?php e(t('This will expire all remember-me tokens immediately and force users to sign in again.')); ?></small>
                </blockquote>
                <button type="submit" class="danger" formnovalidate
                  formaction="admin/settings/expire-remember-tokens"
                  formmethod="post"
                  data-detail-confirm-message="<?php e(t('Expire all login tokens?')); ?>"
                  data-detail-action-kind="danger">
                  <?php e(t('Expire all login tokens')); ?>
                </button>
              </div>
            </details>
          </div>
        <?php endif; ?>
      </div>

      <?php Session::getCsrfInput(); ?>
    </form>
  </section>
  <aside id="app-details-aside-section">
    <div class="app-details-aside-section">
      <div class="entity-avatar-block avatar-square avatar-ratio-16-9 avatar-borderless">
        <a data-fslightbox="app-logo" href="<?php e(appLogoUrl(256)); ?>">
          <img class="entity-avatar-image" src="<?php e(appLogoUrl(256)); ?>" alt="<?php e(t('App logo')); ?>">
        </a>
      </div>
      <hgroup>
        <h2><?php e(appTitle()); ?></h2>
        <p><?php e(t('Settings')); ?></p>
      </hgroup>
      <hr>
      <?php if ($canUpdateSettings): ?>
        <details name="app-logo">
          <summary>
            <?php e(t('Upload logo')); ?>
          </summary>
          <hr>
          <small>
            <?php e(t('Allowed file types: SVG, PNG, JPG, WEBP')); ?>
          </small>
          <hr>
          <form class="user-avatar-form" method="post" action="admin/settings/logo" enctype="multipart/form-data">
            <label class="user-avatar-upload">
              <input type="file" name="logo" accept="image/svg+xml,image/png,image/jpeg,image/webp">
            </label>
            <div class="grid">
              <button type="submit" class="primary">
                <?php e(t('Save')); ?>
              </button>
              <?php if ($hasLogo): ?>
                <button type="submit" class="danger" formaction="admin/settings/logo-delete" formmethod="post">
                  <?php e(t('Remove logo')); ?>
                </button>
              <?php endif; ?>
            </div>
            <?php Session::getCsrfInput(); ?>
          </form>
        </details>
      <?php endif; ?>
      <hr>
      <?php if ($canUpdateSettings): ?>
        <details name="app-favicon">
          <summary>
            <?php e(t('Upload favicon')); ?>
          </summary>
          <hr>
          <?php if ($hasFavicon): ?>
            <div class="entity-avatar-block avatar-square avatar-borderless" style="--avatar-size: 48px;">
              <img class="entity-avatar-image" src="<?php e(asset('favicon/favicon-32x32.png')); ?>"
                alt="<?php e(t('Favicon')); ?>">
            </div>
            <small><?php e(t('Favicon preview')); ?></small>
            <hr>
          <?php endif; ?>
          <small><?php e(t('Allowed file types: PNG')); ?></small>
          <small><?php e(t('Square images are recommended (icons are center-cropped).')); ?></small>
          <hr>
          <form class="user-avatar-form" method="post" action="admin/settings/favicon" enctype="multipart/form-data">
            <label class="user-avatar-upload">
              <input type="file" name="favicon" accept="image/png">
            </label>
            <div class="grid">
              <button type="submit" class="primary">
                <?php e(t('Save')); ?>
              </button>
              <?php if ($hasFavicon): ?>
                <button type="submit" class="danger" formaction="admin/settings/favicon-delete" formmethod="post">
                  <?php e(t('Remove favicon')); ?>
                </button>
              <?php endif; ?>
            </div>
            <?php Session::getCsrfInput(); ?>
          </form>
        </details>
      <?php endif; ?>
      <hr>
      <blockquote data-variant="info">
        <?php e(t('Global settings are stored in the database. config/settings.php is only a runtime cache for selected app settings.')); ?>
      </blockquote>
    </div>
  </aside>
</div>
