<?php

/**
 * @var array $values
 * @var array $settings
 * @var int   $activeApiTokens
 * @var bool  $canUpdateSettings
 */

use MintyPHP\Session;

$values = $values ?? [];
$settings = $settings ?? [];
$apiTokenDefaultTtlDays = (int) ($values['api_token_default_ttl_days'] ?? 90);
$apiTokenMaxTtlDays = (int) ($values['api_token_max_ttl_days'] ?? 365);
$apiCorsAllowedOrigins = (string) ($values['api_cors_allowed_origins'] ?? '');
$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';
$apiCorsAllowedOriginsDesc = $settings['api_cors_allowed_origins']['description'] ?? 'setting.api_cors_allowed_origins';
$activeApiTokens = (int) ($activeApiTokens ?? 0);
$canUpdateSettings = (bool) ($canUpdateSettings ?? false);
$isReadOnly = !$canUpdateSettings;
$readonlyAttr = $isReadOnly ? 'readonly' : '';
?>

<div class="app-details-container">
  <section>
    <?php
    $titlebar = [
      'title' => t('API settings'),
      'backHref' => 'admin/settings',
      'backTitle' => t('Cancel'),
      'actions' => $canUpdateSettings ? [
        [
          'form' => 'settings-api-form',
          'name' => 'action',
          'value' => 'save',
          'class' => 'secondary outline',
          'label' => t('Save'),
        ],
        [
          'form' => 'settings-api-form',
          'name' => 'action',
          'value' => 'save_close',
          'class' => 'primary',
          'label' => t('Save & close'),
        ],
      ] : [],
    ];
    require templatePath('partials/app-details-titlebar.phtml');
    ?>

    <form id="settings-api-form" method="post" data-details-storage="settings-api-details-v1" data-standard-detail-form="1">
      <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">
          <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">
          <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>
        </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; ?>

      <?php Session::getCsrfInput(); ?>
    </form>
  </section>
  <aside id="app-details-aside-section">
    <div class="app-details-aside-section"></div>
  </aside>
</div>
