<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';

$currentUser = myronRequireAdministrationAccess();
$csrfToken = myronCsrfToken();
$settingsRepo = myronVerificationSettingsRepository();
$logsRepo = myronVerificationLogRepository();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        if ($action === 'save-verification-settings') {
            $settingsRepo->saveSettings([
                'verification_enabled' => isset($_POST['verification_enabled']),
                'verification_provider' => (string) ($_POST['verification_provider'] ?? 'native'),
                'verification_risk_threshold' => (int) ($_POST['verification_risk_threshold'] ?? 50),
                'verification_challenge_enabled' => isset($_POST['verification_challenge_enabled']),
                'verification_rate_limit_per_hour' => (int) ($_POST['verification_rate_limit_per_hour'] ?? 10),
                'verification_turnstile_site_key' => (string) ($_POST['verification_turnstile_site_key'] ?? ''),
                'verification_turnstile_secret_key' => (string) ($_POST['verification_turnstile_secret_key'] ?? ''),
                'verification_fail_open' => isset($_POST['verification_fail_open']),
            ]);
            myronRedirectWithFlash(myronBuildAdminUrl('administration.formProtection'), 'Form protection settings saved.', 'success');
        }
        if (isset($_POST['cleanup_verification_logs'])) {
            $removedLogs = $logsRepo->purgeOlderThanDays(90);
            $removedChallenges = myronVerificationChallengeStore()->cleanup();
            myronRedirectWithFlash(
                myronBuildAdminUrl('administration.formProtection'),
                'Verification cleanup removed ' . ($removedLogs + $removedChallenges) . ' stale records.',
                'success'
            );
        }
        throw new RuntimeException('Unknown form protection action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('administration.formProtection'), $exception->getMessage(), 'error');
    }
}

$settings = $settingsRepo->getSettings();
$logs = $logsRepo->recent(25);

myronRenderAdminShellStart($currentUser, [
    'title' => 'Form Protection',
    'titleContext' => 'Administration',
    'activeItem' => 'form-protection',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'System', 'href' => myronBuildAdminUrl('administration.siteSetup')],
      ['label' => 'Form Protection'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Form Protection</h1>
  </div>
  <p class="mc-workspace__subtitle">Configure the native verification engine used by public forms.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <h2 class="sg-section__title">Settings</h2>
      <form class="sg-form-grid" method="post" action="<?= myronEscape(myronBuildAdminUrl('administration.formProtection')) ?>">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="save-verification-settings">

        <label class="sg-field">
          <span class="sg-field__label">Protection Enabled</span>
          <span><input type="checkbox" name="verification_enabled" value="1"<?= !empty($settings['verification_enabled']) ? ' checked' : '' ?>> Enable form protection</span>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Provider</span>
          <select class="sg-field__control" name="verification_provider">
            <?php foreach (['native' => 'Native', 'turnstile' => 'Cloudflare Turnstile', 'recaptcha' => 'reCAPTCHA Stub', 'hcaptcha' => 'hCaptcha Stub'] as $value => $label): ?>
              <option value="<?= myronEscape($value) ?>"<?= (string) ($settings['verification_provider'] ?? 'native') === $value ? ' selected' : '' ?>><?= myronEscape($label) ?></option>
            <?php endforeach; ?>
          </select>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Risk Threshold</span>
          <input class="sg-field__control" type="number" name="verification_risk_threshold" min="1" max="100" value="<?= (int) ($settings['verification_risk_threshold'] ?? 50) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Rate Limit</span>
          <input class="sg-field__control" type="number" name="verification_rate_limit_per_hour" min="1" max="200" value="<?= (int) ($settings['verification_rate_limit_per_hour'] ?? 10) ?>">
          <span class="sg-field__help">Attempts per form per hashed IP per hour.</span>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Native Challenge</span>
          <span><input type="checkbox" name="verification_challenge_enabled" value="1"<?= !empty($settings['verification_challenge_enabled']) ? ' checked' : '' ?>> Require accessible choice challenge</span>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Fail Open</span>
          <span><input type="checkbox" name="verification_fail_open" value="1"<?= !empty($settings['verification_fail_open']) ? ' checked' : '' ?>> Allow submissions if signing key is unavailable</span>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Turnstile Site Key</span>
          <input class="sg-field__control" type="text" name="verification_turnstile_site_key" value="<?= myronEscape((string) ($settings['verification_turnstile_site_key'] ?? '')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Turnstile Secret Key</span>
          <input class="sg-field__control" type="password" name="verification_turnstile_secret_key" value="<?= myronEscape((string) ($settings['verification_turnstile_secret_key'] ?? '')) ?>" autocomplete="off">
        </label>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Save Settings</button>
        </div>
      </form>
    </section>

    <section class="sg-section">
      <div class="mc-workspace__title-row">
        <h2 class="sg-section__title">Recent Verification Log</h2>
        <form method="post" action="<?= myronEscape(myronBuildAdminUrl('administration.formProtection')) ?>">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <button class="sg-button sg-button--secondary" name="cleanup_verification_logs" value="1" type="submit">Run Cleanup</button>
        </form>
      </div>
      <table class="mc-page-grid">
        <thead><tr><th>When</th><th>Form</th><th>Outcome</th><th>Risk</th><th>Provider</th><th>Signals</th></tr></thead>
        <tbody>
        <?php foreach ($logs as $log): ?>
          <tr>
            <td><?= myronEscape((string) ($log['created_at'] ?? '')) ?></td>
            <td><code><?= myronEscape((string) ($log['form_key'] ?? '')) ?></code></td>
            <td><?= myronEscape((string) ($log['outcome'] ?? '')) ?></td>
            <td><?= (int) ($log['risk_score'] ?? 0) ?></td>
            <td><?= myronEscape((string) ($log['provider'] ?? '')) ?></td>
            <td><?= myronEscape(implode(', ', (array) ($log['reasons'] ?? []))) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if ($logs === []): ?><tr><td colspan="6">No verification events have been recorded.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
