<?php

declare(strict_types=1);

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

$currentUser = myronRequireAdministrationAccess();
$repository = myronMailSettingsRepository();
$mailTestService = myronMailTestService();
$csrfToken = myronCsrfToken();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));

        if ($action === 'save-mail-settings') {
            $repository->saveSettings($_POST);
            myronRedirectWithFlash(myronBuildAdminUrl('administration.mail'), 'Mail settings saved.', 'success');
        }

        if ($action === 'send-test-mail') {
            $recipientEmail = $mailTestService->sendToConfiguredAddress();
            myronRedirectWithFlash(myronBuildAdminUrl('administration.mail'), 'Test email sent to ' . $recipientEmail . '.', 'success');
        }

        throw new RuntimeException('Unknown mail setup action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('administration.mail'), $exception->getMessage(), 'error');
    }
}

$settings = $repository->getSettings();
$appKeyAvailable = myronAppKeyAvailable();

myronRenderAdminShellStart($currentUser, [
    'title' => 'Mail Settings',
    'titleContext' => 'Administration',
    'activeItem' => 'mail-setup',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'Manage', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'Mail Settings'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Mail Settings</h1>
  </div>
  <p class="mc-workspace__subtitle">Configure the SMTP sender connection for transactional mail delivery. Verified Destinations controls where form submissions and workflow notifications are sent.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if (!$appKeyAvailable): ?>
    <div class="sg-status sg-status--error" role="status">
      Configure <code>MYRON_APP_KEY</code> before saving SMTP credentials. Mail secrets are encrypted at rest.
    </div>
    <?php endif; ?>

    <section class="sg-section">
      <div class="mc-mail-setup-summary">
        <div class="mc-page-summary__item">
          <span class="mc-page-summary__label">Status</span>
          <strong><?= $settings !== null ? 'Configured' : 'Not configured' ?></strong>
        </div>
        <div class="mc-page-summary__item">
          <span class="mc-page-summary__label">Security</span>
          <strong><?= myronEscape((string) ($settings['smtp_security'] ?? '—')) ?></strong>
        </div>
        <div class="mc-page-summary__item">
          <span class="mc-page-summary__label">Password</span>
          <strong><?= myronEscape((string) ($settings['password_mask'] ?? 'Not set')) ?></strong>
        </div>
      </div>
    </section>

    <section class="sg-section">
      <p class="sg-section__subtitle">MyronCMS sends mail via SMTP using the sender below. Use Verified Destinations to add the internal addresses that forms and workflows may send to. For reliable deliverability across recipient mail providers, configure SPF, DKIM, and DMARC on your domain's DNS. MyronCMS does not manage DNS on your behalf; consult your mail provider's documentation for the records they require.</p>
      <?php if (is_array($settings) && !$repository->senderDomainMatchesInstallDomain((string) ($settings['from_email'] ?? ''))): ?>
      <div class="sg-status sg-status--warning" role="status">The saved From Email does not match this install domain. Update it before saving changes.</div>
      <?php endif; ?>
      <form method="post" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">

        <label class="sg-field">
          <span class="sg-field__label">SMTP Host</span>
          <input class="sg-field__control" type="text" name="smtp_host" required value="<?= myronEscape((string) ($settings['smtp_host'] ?? '')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">SMTP Port</span>
          <input class="sg-field__control" type="number" name="smtp_port" required value="<?= myronEscape((string) ($settings['smtp_port'] ?? '587')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Security</span>
          <select class="sg-field__control" name="smtp_security">
            <?php foreach (['none', 'ssl', 'tls'] as $security): ?>
            <option value="<?= myronEscape($security) ?>"<?= (string) ($settings['smtp_security'] ?? 'tls') === $security ? ' selected' : '' ?>><?= strtoupper($security) ?></option>
            <?php endforeach; ?>
          </select>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">SMTP Username</span>
          <input class="sg-field__control" type="text" name="smtp_username" required value="<?= myronEscape((string) ($settings['smtp_username'] ?? '')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">SMTP Password</span>
          <input class="sg-field__control" type="password" name="smtp_password" placeholder="<?= $settings !== null ? 'Leave blank to keep existing secret' : 'Required' ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">From Email</span>
          <input class="sg-field__control" type="email" name="from_email" required value="<?= myronEscape((string) ($settings['from_email'] ?? '')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">From Name</span>
          <input class="sg-field__control" type="text" name="from_name" required value="<?= myronEscape((string) ($settings['from_name'] ?? '')) ?>">
        </label>

        <div class="sg-card__actions">
          <button class="sg-button" type="submit" name="action" value="send-test-mail" formnovalidate<?= $repository->isConfigured() ? '' : ' disabled' ?>>Send Test Email</button>
          <button class="sg-button sg-button--primary" type="submit" name="action" value="save-mail-settings"<?= $appKeyAvailable ? '' : ' disabled' ?>>Save Mail Settings</button>
          <span class="sg-inline-note">Uses saved settings and sends to <?= myronEscape((string) ($settings['from_email'] ?? 'the configured From Email address')) ?>.</span>
        </div>
      </form>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
