<?php

/**
 * @var string $authMode
 * @var string $odataBaseUrl
 * @var string $companyName
 * @var string $basicUser
 * @var bool $hasBasicPassword
 * @var string $oauthTenantId
 * @var string $oauthClientId
 * @var bool $hasOAuthClientSecret
 * @var string $oauthTokenEndpoint
 * @var array $configErrors
 * @var array $recommendationsConfig
 * @var string $recommendationsConfigSource
 * @var array $controllingConfig
 * @var string $controllingConfigSource
 * @var int $currentTenantId
 * @var string $currentTenantName
 * @var bool $tenantOverrideEnabled
 * @var array|null $tenantRow
 * @var bool $tenantHasBasicPassword
 * @var bool $tenantHasOAuthSecret
 */

use MintyPHP\Module\Helpdesk\Service\HelpdeskSettingsGateway;
use MintyPHP\Session;

$authMode = $authMode ?? HelpdeskSettingsGateway::AUTH_MODE_BASIC;
$odataBaseUrl = $odataBaseUrl ?? HelpdeskSettingsGateway::DEFAULT_ODATA_BASE_URL;
$companyName = $companyName ?? HelpdeskSettingsGateway::DEFAULT_COMPANY_NAME;
$basicUser = $basicUser ?? '';
$hasBasicPassword = $hasBasicPassword ?? false;
$oauthTenantId = $oauthTenantId ?? '';
$oauthClientId = $oauthClientId ?? '';
$hasOAuthClientSecret = $hasOAuthClientSecret ?? false;
$oauthTokenEndpoint = $oauthTokenEndpoint ?? '';
$configErrors = is_array($configErrors ?? null) ? $configErrors : [];
$recommendationsConfig = is_array($recommendationsConfig ?? null) ? $recommendationsConfig : [];
$recommendationsConfigSource = (string) ($recommendationsConfigSource ?? 'default');
$recommendationsMaxItems = (int) ($recommendationsConfig['max_items'] ?? 5);
$recommendationRules = is_array($recommendationsConfig['rules'] ?? null) ? $recommendationsConfig['rules'] : [];
$ruleEscalationOverdue = is_array($recommendationRules['escalation_overdue'] ?? null) ? $recommendationRules['escalation_overdue'] : [];
$ruleHighRiskAging = is_array($recommendationRules['high_risk_aging'] ?? null) ? $recommendationRules['high_risk_aging'] : [];
$ruleUnassignedOpen = is_array($recommendationRules['unassigned_open'] ?? null) ? $recommendationRules['unassigned_open'] : [];
$ruleStaleOpen = is_array($recommendationRules['stale_open'] ?? null) ? $recommendationRules['stale_open'] : [];
$ruleCustomerBacklog = is_array($recommendationRules['customer_backlog'] ?? null) ? $recommendationRules['customer_backlog'] : [];
$highRiskCodes = is_array($ruleHighRiskAging['codes'] ?? null) ? implode(',', $ruleHighRiskAging['codes']) : 'MAX,HOCH';
$controllingConfig = is_array($controllingConfig ?? null) ? $controllingConfig : [];
$controllingConfigSource = (string) ($controllingConfigSource ?? 'default');
$controllingRules = is_array($controllingConfig['rules'] ?? null) ? $controllingConfig['rules'] : [];
$ctrlTicketVolume = is_array($controllingRules['ticket_volume_increase'] ?? null) ? $controllingRules['ticket_volume_increase'] : [];
$ctrlAvgResolution = is_array($controllingRules['avg_resolution_high'] ?? null) ? $controllingRules['avg_resolution_high'] : [];
$ctrlOpenAging = is_array($controllingRules['open_aging'] ?? null) ? $controllingRules['open_aging'] : [];
$ctrlUnassigned = is_array($controllingRules['unassigned_ratio'] ?? null) ? $controllingRules['unassigned_ratio'] : [];
$isOAuth2 = $authMode === HelpdeskSettingsGateway::AUTH_MODE_OAUTH2;
$currentTenantId = (int) ($currentTenantId ?? 0);
$currentTenantName = (string) ($currentTenantName ?? '');
$tenantOverrideEnabled = (bool) ($tenantOverrideEnabled ?? false);
$tenantRow = is_array($tenantRow ?? null) ? $tenantRow : [];
$tenantHasBasicPassword = (bool) ($tenantHasBasicPassword ?? false);
$tenantHasOAuthSecret = (bool) ($tenantHasOAuthSecret ?? false);
$tenantAuthMode = trim((string) ($tenantRow['auth_mode'] ?? HelpdeskSettingsGateway::AUTH_MODE_BASIC));
$tenantIsOAuth2 = $tenantAuthMode === HelpdeskSettingsGateway::AUTH_MODE_OAUTH2;
?>
<div class="app-details-container" data-app-component="helpdesk-settings">
  <section>
    <?php
    $titlebar = [
        'title' => t('Helpdesk settings'),
        'backHref' => lurl('helpdesk'),
        'actions' => [
            [
                'label' => t('Save'),
                'type' => 'submit',
                'form' => 'helpdesk-settings-form',
                'name' => 'action',
                'value' => 'save',
                'class' => 'primary',
                'detailSavePrimary' => true,
                'detailActionKind' => 'save',
            ],
            [
                'label' => t('Save & close'),
                'type' => 'submit',
                'form' => 'helpdesk-settings-form',
                'name' => 'action',
                'value' => 'save_close',
                'class' => 'secondary outline',
            ],
        ],
    ];
    require templatePath('partials/app-details-titlebar.phtml');
    ?>

    <?php if ($configErrors !== []): ?>
      <div class="notice" data-variant="warning" role="alert">
        <strong><?php e(t('Configuration incomplete')); ?>:</strong>
        <ul>
          <?php foreach ($configErrors as $err): ?>
            <li><?php e($err); ?></li>
          <?php endforeach; ?>
        </ul>
      </div>
    <?php endif; ?>

    <?php if ($recommendationsConfigSource === 'fallback_invalid_json' || $controllingConfigSource === 'fallback_invalid_json'): ?>
      <div class="notice" data-variant="warning" role="alert">
        <p><?php e(t('Automation configuration was invalid. Defaults were applied.')); ?></p>
      </div>
    <?php endif; ?>

    <form
      id="helpdesk-settings-form"
      method="post"
      action="<?php e(lurl('helpdesk/settings')); ?>"
      data-standard-detail-form="1"
      data-details-storage="helpdesk-settings-main-details-v1"
      data-test-success-message="<?php e(t('Connection successful')); ?>"
      data-test-error-message="<?php e(t('Connection failed')); ?>"
      data-test-loading-label="<?php e(t('Testing...')); ?>"
      data-test-default-label="<?php e(t('Test connection')); ?>"
    >
      <?php Session::getCsrfInput(); ?>
      <input type="hidden" name="save_target" value="global" id="helpdesk-settings-save-target">

      <div class="app-tabs" data-tabs data-app-component="tabs" data-tabs-param="tab" data-tabs-storage-key="helpdesk-settings-tabs-v3">
        <div class="app-tabs-nav">
          <button type="button" data-tab="global" data-tab-default><?php e(t('General connection')); ?></button>
          <?php if ($currentTenantId > 0): ?>
            <button type="button" data-tab="tenant"><?php e(t('Tenant connection')); ?></button>
          <?php endif; ?>
          <button type="button" data-tab="automation"><?php e(t('Automation')); ?></button>
        </div>

        <!-- ═══════════════ GLOBAL TAB ═══════════════ -->
        <div data-tab-panel="global" class="helpdesk-settings-panel">
          <?php if ($currentTenantId > 0 && $tenantOverrideEnabled): ?>
            <div class="notice" data-variant="info" role="status">
              <p><?php e(t('The current tenant uses its own configuration. Changes here only affect tenants without a tenant-specific connection.')); ?></p>
            </div>
          <?php endif; ?>

          <details class="app-details-card" name="helpdesk-global-connection" data-details-key="helpdesk-settings-global-connection" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Connection')); ?></span>
            </summary>
            <div class="app-details-card-container">
              <label class="app-field" for="odata_base_url">
                <span><?php e(t('OData Base URL')); ?></span>
                <input
                  type="url"
                  id="odata_base_url"
                  name="odata_base_url"
                  value="<?php e($odataBaseUrl); ?>"
                  placeholder="https://bc.example.com:7048/BusinessCentral/ODataV4"
                >
                <small><?php e(t('Base URL without Company path segment')); ?></small>
              </label>

              <label class="app-field" for="company_name">
                <span><?php e(t('Company name')); ?></span>
                <input
                  type="text"
                  id="company_name"
                  name="company_name"
                  value="<?php e($companyName); ?>"
                  placeholder="<?php e(HelpdeskSettingsGateway::DEFAULT_COMPANY_NAME); ?>"
                >
                <small><?php e(t('BC company name (URL-encoded automatically)')); ?></small>
              </label>
            </div>
          </details>

          <details class="app-details-card" name="helpdesk-global-auth" data-details-key="helpdesk-settings-global-auth" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Authentication')); ?></span>
            </summary>
            <div class="app-details-card-container">
              <label class="app-field" for="auth_mode">
                <span><?php e(t('Auth mode')); ?></span>
                <select id="auth_mode" name="auth_mode">
                  <option value="<?php e(HelpdeskSettingsGateway::AUTH_MODE_BASIC); ?>" <?php if (!$isOAuth2): ?>selected<?php endif; ?>>
                    <?php e(t('Basic Auth')); ?>
                  </option>
                  <option value="<?php e(HelpdeskSettingsGateway::AUTH_MODE_OAUTH2); ?>" <?php if ($isOAuth2): ?>selected<?php endif; ?>>
                    <?php e(t('OAuth2 (client credentials)')); ?>
                  </option>
                </select>
              </label>

              <div id="helpdesk-basic-auth-fields" class="helpdesk-settings-rule-grid" <?php if ($isOAuth2): ?>hidden<?php endif; ?>>
                <label class="app-field" for="basic_user">
                  <span><?php e(t('Username')); ?></span>
                  <input type="text" id="basic_user" name="basic_user" value="<?php e($basicUser); ?>" autocomplete="off">
                </label>
                <label class="app-field" for="basic_password">
                  <span><?php e(t('Password')); ?></span>
                  <input type="password" id="basic_password" name="basic_password" value="" placeholder="<?php if ($hasBasicPassword): ?><?php e(t('Saved')); ?><?php endif; ?>" autocomplete="new-password">
                  <?php if ($hasBasicPassword): ?>
                    <small><?php e(t('Leave empty to keep current password')); ?></small>
                  <?php endif; ?>
                </label>
              </div>

              <div id="helpdesk-oauth2-fields" class="helpdesk-settings-rule-grid" <?php if (!$isOAuth2): ?>hidden<?php endif; ?>>
                <label class="app-field" for="oauth_tenant_id">
                  <span><?php e(t('Azure Tenant ID')); ?></span>
                  <input type="text" id="oauth_tenant_id" name="oauth_tenant_id" value="<?php e($oauthTenantId); ?>" autocomplete="off">
                </label>
                <label class="app-field" for="oauth_client_id">
                  <span><?php e(t('Client ID')); ?></span>
                  <input type="text" id="oauth_client_id" name="oauth_client_id" value="<?php e($oauthClientId); ?>" autocomplete="off">
                </label>
                <label class="app-field" for="oauth_client_secret">
                  <span><?php e(t('Client Secret')); ?></span>
                  <input type="password" id="oauth_client_secret" name="oauth_client_secret" value="" placeholder="<?php if ($hasOAuthClientSecret): ?><?php e(t('Saved')); ?><?php endif; ?>" autocomplete="new-password">
                  <?php if ($hasOAuthClientSecret): ?>
                    <small><?php e(t('Leave empty to keep current password')); ?></small>
                  <?php endif; ?>
                </label>
                <label class="app-field" for="oauth_token_endpoint">
                  <span><?php e(t('Token endpoint URL')); ?></span>
                  <input type="url" id="oauth_token_endpoint" name="oauth_token_endpoint" value="<?php e($oauthTokenEndpoint); ?>" placeholder="https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token">
                </label>
              </div>
            </div>
          </details>

          <details class="app-details-card" name="helpdesk-global-test" data-details-key="helpdesk-settings-global-test" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Connection test')); ?></span>
            </summary>
            <div class="app-details-card-container">
              <button
                type="button"
                id="helpdesk-test-connection-button"
                class="secondary outline"
                data-label-default="<?php e(t('Test connection')); ?>"
                data-label-loading="<?php e(t('Testing...')); ?>"
              >
                <?php e(t('Test connection')); ?>
              </button>
              <div id="helpdesk-connection-test-result" class="notice helpdesk-settings-test-result" data-variant="info" role="status" aria-live="polite" hidden></div>
            </div>
          </details>
        </div>

        <!-- ═══════════════ TENANT TAB ═══════════════ -->
        <?php if ($currentTenantId > 0): ?>
        <div data-tab-panel="tenant" class="helpdesk-settings-panel">
          <details class="app-details-card" name="helpdesk-tenant-override" data-details-key="helpdesk-settings-tenant-override" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Configuration source')); ?></span>
            </summary>
            <div class="app-details-card-container">
              <label class="helpdesk-settings-rule">
                <input
                  type="checkbox"
                  role="switch"
                  name="override_enabled"
                  id="helpdesk-override-toggle"
                  <?php if ($tenantOverrideEnabled): ?>checked<?php endif; ?>
                >
                <span class="helpdesk-settings-rule-label"><?php e(t('Use tenant-specific configuration')); ?></span>
                <small><?php e(t('When enabled, this tenant uses its own BC connection instead of the global configuration.')); ?></small>
              </label>
            </div>
          </details>

          <div id="helpdesk-tenant-fields" <?php if (!$tenantOverrideEnabled): ?>hidden<?php endif; ?>>
            <details class="app-details-card" name="helpdesk-tenant-connection" data-details-key="helpdesk-settings-tenant-connection" open>
              <summary>
                <span class="app-details-card-summary-title"><?php e(t('Connection')); ?></span>
              </summary>
              <div class="app-details-card-container">
                <label class="app-field" for="tenant_odata_base_url">
                  <span><?php e(t('OData Base URL')); ?></span>
                  <input type="url" id="tenant_odata_base_url" name="tenant_odata_base_url" value="<?php e(trim((string) ($tenantRow['odata_base_url'] ?? ''))); ?>" placeholder="https://bc.example.com:7048/BusinessCentral/ODataV4">
                </label>
                <label class="app-field" for="tenant_company_name">
                  <span><?php e(t('Company name')); ?></span>
                  <input type="text" id="tenant_company_name" name="tenant_company_name" value="<?php e(trim((string) ($tenantRow['company_name'] ?? ''))); ?>">
                </label>
              </div>
            </details>

            <details class="app-details-card" name="helpdesk-tenant-auth" data-details-key="helpdesk-settings-tenant-auth" open>
              <summary>
                <span class="app-details-card-summary-title"><?php e(t('Authentication')); ?></span>
              </summary>
              <div class="app-details-card-container">
                <label class="app-field" for="tenant_auth_mode">
                  <span><?php e(t('Auth mode')); ?></span>
                  <select id="tenant_auth_mode" name="tenant_auth_mode">
                    <option value="<?php e(HelpdeskSettingsGateway::AUTH_MODE_BASIC); ?>" <?php if (!$tenantIsOAuth2): ?>selected<?php endif; ?>>
                      <?php e(t('Basic Auth')); ?>
                    </option>
                    <option value="<?php e(HelpdeskSettingsGateway::AUTH_MODE_OAUTH2); ?>" <?php if ($tenantIsOAuth2): ?>selected<?php endif; ?>>
                      <?php e(t('OAuth2 (client credentials)')); ?>
                    </option>
                  </select>
                </label>

                <div id="helpdesk-tenant-basic-auth-fields" class="helpdesk-settings-rule-grid" <?php if ($tenantIsOAuth2): ?>hidden<?php endif; ?>>
                  <label class="app-field" for="tenant_basic_user">
                    <span><?php e(t('Username')); ?></span>
                    <input type="text" id="tenant_basic_user" name="tenant_basic_user" value="<?php e(trim((string) ($tenantRow['basic_user'] ?? ''))); ?>" autocomplete="off">
                  </label>
                  <label class="app-field" for="tenant_basic_password">
                    <span><?php e(t('Password')); ?></span>
                    <input type="password" id="tenant_basic_password" name="tenant_basic_password" value="" placeholder="<?php if ($tenantHasBasicPassword): ?><?php e(t('Saved')); ?><?php endif; ?>" autocomplete="new-password">
                    <?php if ($tenantHasBasicPassword): ?>
                      <small><?php e(t('Leave empty to keep current password')); ?></small>
                    <?php endif; ?>
                  </label>
                </div>

                <div id="helpdesk-tenant-oauth2-fields" class="helpdesk-settings-rule-grid" <?php if (!$tenantIsOAuth2): ?>hidden<?php endif; ?>>
                  <label class="app-field" for="tenant_oauth_tenant_id">
                    <span><?php e(t('Azure Tenant ID')); ?></span>
                    <input type="text" id="tenant_oauth_tenant_id" name="tenant_oauth_tenant_id" value="<?php e(trim((string) ($tenantRow['oauth_tenant_id'] ?? ''))); ?>" autocomplete="off">
                  </label>
                  <label class="app-field" for="tenant_oauth_client_id">
                    <span><?php e(t('Client ID')); ?></span>
                    <input type="text" id="tenant_oauth_client_id" name="tenant_oauth_client_id" value="<?php e(trim((string) ($tenantRow['oauth_client_id'] ?? ''))); ?>" autocomplete="off">
                  </label>
                  <label class="app-field" for="tenant_oauth_client_secret">
                    <span><?php e(t('Client Secret')); ?></span>
                    <input type="password" id="tenant_oauth_client_secret" name="tenant_oauth_client_secret" value="" placeholder="<?php if ($tenantHasOAuthSecret): ?><?php e(t('Saved')); ?><?php endif; ?>" autocomplete="new-password">
                    <?php if ($tenantHasOAuthSecret): ?>
                      <small><?php e(t('Leave empty to keep current password')); ?></small>
                    <?php endif; ?>
                  </label>
                  <label class="app-field" for="tenant_oauth_token_endpoint">
                    <span><?php e(t('Token endpoint URL')); ?></span>
                    <input type="url" id="tenant_oauth_token_endpoint" name="tenant_oauth_token_endpoint" value="<?php e(trim((string) ($tenantRow['oauth_token_endpoint'] ?? ''))); ?>" placeholder="https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token">
                  </label>
                </div>
              </div>
            </details>
          </div>

          <?php if (!$tenantOverrideEnabled): ?>
            <div class="notice" data-variant="info" role="status">
              <p><?php e(t('This tenant inherits the global configuration. Enable the toggle above to use tenant-specific settings.')); ?></p>
            </div>
          <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- ═══════════════ AUTOMATION TAB ═══════════════ -->
        <div data-tab-panel="automation" class="helpdesk-settings-panel">
          <details class="app-details-card" name="helpdesk-recommendations" data-details-key="helpdesk-settings-recommendations-v2" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Recommendations')); ?></span>
            </summary>
            <div class="app-details-card-container">
              <label class="app-field" for="recommendations_max_items">
                <span><?php e(t('Maximum recommendations')); ?></span>
                <input type="number" id="recommendations_max_items" name="recommendations_max_items" min="1" max="20" value="<?php e($recommendationsMaxItems); ?>">
              </label>

              <div class="helpdesk-settings-rules">
                <label class="helpdesk-settings-rule">
                  <input type="checkbox" role="switch" name="recommendations_escalation_overdue_enabled" <?php if (($ruleEscalationOverdue['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                  <span class="helpdesk-settings-rule-label"><?php e(t('Escalation overdue')); ?></span>
                  <small><?php e(t('rule_help_escalation_overdue')); ?></small>
                </label>
                <hr>
                <label class="helpdesk-settings-rule">
                  <input type="checkbox" role="switch" name="recommendations_high_risk_aging_enabled" <?php if (($ruleHighRiskAging['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                  <span class="helpdesk-settings-rule-label"><?php e(t('High-risk aging')); ?></span>
                  <small><?php e(t('rule_help_high_risk_aging')); ?></small>
                </label>
                <hr>
                <label class="helpdesk-settings-rule">
                  <input type="checkbox" role="switch" name="recommendations_unassigned_open_enabled" <?php if (($ruleUnassignedOpen['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                  <span class="helpdesk-settings-rule-label"><?php e(t('Unassigned open')); ?></span>
                  <small><?php e(t('rule_help_unassigned_open')); ?></small>
                </label>
                <hr>
                <label class="helpdesk-settings-rule">
                  <input type="checkbox" role="switch" name="recommendations_stale_open_enabled" <?php if (($ruleStaleOpen['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                  <span class="helpdesk-settings-rule-label"><?php e(t('Stale open')); ?></span>
                  <small><?php e(t('rule_help_stale_open')); ?></small>
                </label>
                <hr>
                <label class="helpdesk-settings-rule">
                  <input type="checkbox" role="switch" name="recommendations_customer_backlog_enabled" <?php if (($ruleCustomerBacklog['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                  <span class="helpdesk-settings-rule-label"><?php e(t('Customer backlog')); ?></span>
                  <small><?php e(t('rule_help_customer_backlog')); ?></small>
                </label>
              </div>

              <hr>
              <details class="helpdesk-settings-advanced" data-details-key="helpdesk-settings-recommendations-advanced">
                <summary><?php e(t('Advanced options')); ?></summary>
                <div class="helpdesk-settings-advanced-grid">
                  <label class="app-field">
                    <span><?php e(t('Min. overdue')); ?> (min)</span>
                    <input type="number" name="recommendations_escalation_overdue_min_overdue_minutes" min="0" max="43200" value="<?php e((int) ($ruleEscalationOverdue['min_overdue_minutes'] ?? 0)); ?>">
                  </label>
                  <label class="app-field">
                    <span><?php e(t('High-risk codes (comma separated)')); ?></span>
                    <input type="text" name="recommendations_high_risk_aging_codes" value="<?php e($highRiskCodes); ?>">
                  </label>
                  <label class="app-field">
                    <span><?php e(t('Min. age')); ?> — <?php e(t('High-risk aging')); ?> (h)</span>
                    <input type="number" name="recommendations_high_risk_aging_min_age_hours" min="0" max="720" value="<?php e((int) ($ruleHighRiskAging['min_age_hours'] ?? 8)); ?>">
                  </label>
                  <label class="app-field">
                    <span><?php e(t('Min. age')); ?> — <?php e(t('Unassigned open')); ?> (h)</span>
                    <input type="number" name="recommendations_unassigned_open_min_age_hours" min="0" max="720" value="<?php e((int) ($ruleUnassignedOpen['min_age_hours'] ?? 2)); ?>">
                  </label>
                  <label class="app-field">
                    <span><?php e(t('Min. age')); ?> — <?php e(t('Stale open')); ?> (h)</span>
                    <input type="number" name="recommendations_stale_open_min_age_hours" min="0" max="1440" value="<?php e((int) ($ruleStaleOpen['min_age_hours'] ?? 48)); ?>">
                  </label>
                  <label class="app-field">
                    <span><?php e(t('Min. open')); ?> — <?php e(t('Customer backlog')); ?></span>
                    <input type="number" name="recommendations_customer_backlog_min_open_tickets" min="1" max="500" value="<?php e((int) ($ruleCustomerBacklog['min_open_tickets'] ?? 6)); ?>">
                  </label>
                </div>
              </details>
            </div>
          </details>

          <details class="app-details-card" name="helpdesk-risk-monitoring" data-details-key="helpdesk-settings-risk-monitoring-v2" open>
            <summary>
              <span class="app-details-card-summary-title"><?php e(t('Risk monitoring')); ?></span>
            </summary>
            <div class="app-details-card-container">
              <div class="helpdesk-settings-rules">
                <div class="helpdesk-settings-rule helpdesk-settings-rule-with-threshold">
                  <label class="helpdesk-settings-rule-toggle">
                    <input type="checkbox" role="switch" name="controlling_ticket_volume_increase_enabled" <?php if (($ctrlTicketVolume['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                    <span class="helpdesk-settings-rule-label"><?php e(t('Ticket volume increase')); ?></span>
                    <small><?php e(t('rule_help_ticket_volume')); ?></small>
                  </label>
                  <label class="app-field helpdesk-settings-rule-threshold">
                    <span><?php e(t('Threshold (%)')); ?></span>
                    <input type="number" name="controlling_ticket_volume_increase_threshold" min="5" max="200" value="<?php e((int) ($ctrlTicketVolume['threshold_percent'] ?? 30)); ?>">
                  </label>
                </div>
                <hr>
                <div class="helpdesk-settings-rule helpdesk-settings-rule-with-threshold">
                  <label class="helpdesk-settings-rule-toggle">
                    <input type="checkbox" role="switch" name="controlling_avg_resolution_high_enabled" <?php if (($ctrlAvgResolution['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                    <span class="helpdesk-settings-rule-label"><?php e(t('High avg. resolution time')); ?></span>
                    <small><?php e(t('rule_help_avg_resolution')); ?></small>
                  </label>
                  <label class="app-field helpdesk-settings-rule-threshold">
                    <span><?php e(t('Threshold (hours)')); ?></span>
                    <input type="number" name="controlling_avg_resolution_high_threshold" min="1" max="720" value="<?php e((int) ($ctrlAvgResolution['threshold_hours'] ?? 72)); ?>">
                  </label>
                </div>
                <hr>
                <div class="helpdesk-settings-rule helpdesk-settings-rule-with-threshold">
                  <label class="helpdesk-settings-rule-toggle">
                    <input type="checkbox" role="switch" name="controlling_open_aging_enabled" <?php if (($ctrlOpenAging['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                    <span class="helpdesk-settings-rule-label"><?php e(t('Open ticket aging')); ?></span>
                    <small><?php e(t('rule_help_open_aging')); ?></small>
                  </label>
                  <label class="app-field helpdesk-settings-rule-threshold">
                    <span><?php e(t('Threshold (hours)')); ?></span>
                    <input type="number" name="controlling_open_aging_threshold" min="1" max="2160" value="<?php e((int) ($ctrlOpenAging['threshold_hours'] ?? 168)); ?>">
                  </label>
                </div>
                <hr>
                <div class="helpdesk-settings-rule helpdesk-settings-rule-with-threshold">
                  <label class="helpdesk-settings-rule-toggle">
                    <input type="checkbox" role="switch" name="controlling_unassigned_ratio_enabled" <?php if (($ctrlUnassigned['enabled'] ?? true) === true): ?>checked<?php endif; ?>>
                    <span class="helpdesk-settings-rule-label"><?php e(t('Unassigned ticket ratio')); ?></span>
                    <small><?php e(t('rule_help_unassigned_ratio')); ?></small>
                  </label>
                  <label class="app-field helpdesk-settings-rule-threshold">
                    <span><?php e(t('Threshold (%)')); ?></span>
                    <input type="number" name="controlling_unassigned_ratio_threshold" min="1" max="100" value="<?php e((int) ($ctrlUnassigned['threshold_percent'] ?? 20)); ?>">
                  </label>
                </div>
              </div>
            </div>
          </details>
        </div>
      </div>
    </form>
  </section>
</div>
