<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\Auth;
use KeyLair\AuditLog;
use KeyLair\Csrf;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\Mailer;
use KeyLair\Settings;

$admin = Auth::requireAdminTierView();
$isDemo = $admin['role'] === 'demo';

$flash = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($isDemo) {
        http_response_code(403);
        die(I18n::t('mail_settings.demo_readonly'));
    }
    Csrf::requireValid();
    $action = $_POST['form_action'] ?? '';

    if ($action === 'save') {
        $fromAddress = trim($_POST['from_address'] ?? '');
        $fromName = trim($_POST['from_name'] ?? '');

        if ($fromAddress !== '' && !filter_var($fromAddress, FILTER_VALIDATE_EMAIL)) {
            $flash = ['type' => 'error', 'message' => I18n::t('mail_settings.flash.invalid_from_address')];
        } else {
            Settings::set('mail_from_address', $fromAddress !== '' ? $fromAddress : null);
            Settings::set('mail_from_name', $fromName !== '' ? $fromName : null);
            Settings::set('password_reset_enabled', isset($_POST['password_reset_enabled']) ? '1' : '0');
            AuditLog::log($admin['id'], 'mail_settings_updated', null);
            $flash = ['type' => 'success', 'message' => I18n::t('mail_settings.flash.saved')];
        }
    } elseif ($action === 'test') {
        $testAddress = trim($_POST['test_address'] ?? '');
        if (!filter_var($testAddress, FILTER_VALIDATE_EMAIL)) {
            $flash = ['type' => 'error', 'message' => I18n::t('mail_settings.flash.invalid_test_address')];
        } else {
            $sent = Mailer::send(
                $testAddress,
                sprintf(I18n::t('mail_settings.test_email_subject'), Settings::siteName()),
                sprintf(I18n::t('mail_settings.test_email_body'), Settings::siteName())
            );
            AuditLog::log($admin['id'], 'mail_test_sent', $testAddress);
            $flash = $sent
                ? ['type' => 'success', 'message' => sprintf(I18n::t('mail_settings.flash.test_sent'), $testAddress)]
                : ['type' => 'error', 'message' => I18n::t('mail_settings.flash.test_failed')];
        }
    }
}

$fromAddress = Settings::mailFromAddress() ?? '';
$fromName = Settings::mailFromName() ?? '';
$passwordResetEnabled = Settings::passwordResetEnabled();
$transferAgentStatus = Mailer::transferAgentStatus();

$pageTitle = I18n::t('mail_settings.page_title');
$activeNav = 'mail_settings';
$extraAdminCss = 'admin-product-editor';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar"><h1><?= Helpers::e(I18n::t('mail_settings.page_title')) ?></h1></div>

<?php if ($flash): ?>
  <div class="panel" style="border-color:<?= $flash['type'] === 'success' ? 'var(--signal-dim)' : 'var(--danger)' ?>; margin-bottom:16px;">
    <span style="color:<?= $flash['type'] === 'success' ? 'var(--signal)' : 'var(--danger)' ?>; font-size:13px;"><?= Helpers::e($flash['message']) ?></span>
  </div>
<?php endif; ?>

<div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('mail_settings.server_status_title')) ?></p>
    <p class="form-section-hint">
      <?= Helpers::e(I18n::t('mail_settings.server_status_hint')) ?>
    </p>
    <p style="font-size:13px; margin:0;">
      <?= Helpers::e(I18n::t('mail_settings.transfer_agent_label')) ?>
      <?php if ($transferAgentStatus === null): ?>
        <span style="color:var(--text-faint);"><?= Helpers::e(I18n::t('mail_settings.transfer_agent_unknown')) ?></span>
      <?php elseif (str_ends_with($transferAgentStatus, '(active)')): ?>
        <span style="color:var(--signal);"><?= Helpers::e($transferAgentStatus) ?></span>
      <?php else: ?>
        <span style="color:var(--danger);"><?= Helpers::e($transferAgentStatus) ?></span>
      <?php endif; ?>
    </p>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('mail_settings.from_address')) ?></p>
    <form method="post">
      <?= Csrf::field() ?>
      <input type="hidden" name="form_action" value="save">
      <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
      <div class="field-row">
        <div class="field">
          <label><?= Helpers::e(I18n::t('mail_settings.from_address')) ?></label>
          <input type="email" name="from_address" value="<?= Helpers::e($fromAddress) ?>" placeholder="no-reply@yourdomain.com">
        </div>
        <div class="field">
          <label><?= Helpers::e(I18n::t('mail_settings.from_name')) ?></label>
          <input type="text" name="from_name" value="<?= Helpers::e($fromName) ?>" placeholder="<?= Helpers::e(Settings::siteName()) ?>">
        </div>
      </div>
      <div class="field" style="display:flex; align-items:flex-start; gap:8px;">
        <input type="checkbox" name="password_reset_enabled" id="pw-reset-enabled" value="1" style="width:auto; flex-shrink:0; margin-top:3px;" <?= $passwordResetEnabled ? 'checked' : '' ?>>
        <label for="pw-reset-enabled" style="margin:0; cursor:pointer;">
          <?= Helpers::e(I18n::t('mail_settings.password_reset_checkbox_label')) ?>
        </label>
      </div>
      <div class="form-actions" style="padding-bottom:0;"><button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('mail_settings.save_button')) ?></button></div>
      </fieldset>
    </form>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('mail_settings.test_email_title')) ?></p>
    <form method="post">
      <?= Csrf::field() ?>
      <input type="hidden" name="form_action" value="test">
      <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
      <div class="field"><label><?= Helpers::e(I18n::t('mail_settings.test_email_to_label')) ?></label><input type="email" name="test_address" required placeholder="you@example.com"></div>
      <div class="form-actions" style="padding-bottom:0;"><button type="submit" class="btn btn-ghost"><?= Helpers::e(I18n::t('mail_settings.send_test_button')) ?></button></div>
      </fieldset>
    </form>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('mail_settings.install_title')) ?></p>
    <p class="form-section-hint">
      <?= I18n::t('mail_settings.install_hint_html') ?>
    </p>
    <pre style="background:var(--bg-void); border:1px solid var(--line); border-radius:8px; padding:14px; font-family:var(--font-mono); font-size:12px; color:var(--text-primary); white-space:pre-wrap; overflow-wrap:break-word; margin:0;">echo "postfix postfix/main_mailer_type string 'Internet Site'" | sudo debconf-set-selections
echo "postfix postfix/mailname string $(hostname -f)" | sudo debconf-set-selections
sudo apt install -y postfix</pre>
    <p style="font-size:12px; color:var(--text-faint); margin:12px 0 0;">
      <?= I18n::t('mail_settings.install_footer_html') ?>
    </p>
  </div>

</div>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>
