<?php
// Mail tab — Mail Server (incoming/IMAP) configuration, Outbound Email (SMTP)
// settings, and Email Archival (Bichon).
// Variables ($current_config, $mail_server, $mail_api_url, $mail_api_username,
// $mail_api_password) are prepared in the parent server-settings.php before
// the include.
?>

<!-- Mail Server -->
<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Mail Server</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Configure the mail server hostname (used for MX records on new domains) and the API endpoint WHP uses to provision mailboxes.</p>

                <form method="post">
                    <input type="hidden" name="action" value="update_mail_settings">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">

                    <div class="mb-3">
                        <label for="mail_server" class="form-label">Mail Server Hostname</label>
                        <input type="text" class="form-control" id="mail_server" name="mail_server"
                               value="<?php echo ($mail_server !== 'mail.example.com') ? htmlspecialchars($mail_server) : ''; ?>"
                               placeholder="mail.example.com" required>
                        <div class="form-text text-muted">Used for MX records on new domains and as the IMAP host for Bichon archival.</div>
                    </div>

                    <hr>

                    <h6 class="mb-3">Mail Server API</h6>

                    <div class="mb-3">
                        <label for="mail_api_url" class="form-label">Mail API URL</label>
                        <input type="url" class="form-control" id="mail_api_url" name="mail_api_url"
                               value="<?php echo ($mail_api_url !== 'https://your-mail-server.com/admin/api/v1/') ? htmlspecialchars($mail_api_url) : ''; ?>"
                               placeholder="https://your-mail-server.com/admin/api/v1/" required>
                        <div class="form-text text-muted">API endpoint for mail server management.</div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="mail_api_username" class="form-label">Mail API Username</label>
                            <input type="text" class="form-control" id="mail_api_username" name="mail_api_username"
                                   value="<?php echo ($mail_api_username !== 'your-api-username') ? htmlspecialchars($mail_api_username) : ''; ?>"
                                   placeholder="your-api-username" required>
                        </div>
                        <div class="col-md-6">
                            <label for="mail_api_password" class="form-label">Mail API Password</label>
                            <input type="password" class="form-control" id="mail_api_password" name="mail_api_password"
                                   value="<?php echo ($mail_api_password !== 'your-api-password') ? htmlspecialchars($mail_api_password) : ''; ?>"
                                   placeholder="Enter mail server API password" required>
                        </div>
                    </div>

                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="mailserver_debug_log" name="mailserver_debug_log" value="1" <?php if (!empty($current_config['mailserver_debug_log'])) echo 'checked'; ?>>
                        <label class="form-check-label" for="mailserver_debug_log">Enable Mailserver API Debug Logging</label>
                        <div class="form-text text-muted">Log all mailserver API requests and responses to the PHP error log for troubleshooting.</div>
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Save Mail Server Settings
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Outbound Email (SMTP) Settings -->
<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Outbound Email (SMTP)</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Configure SMTP for customer AI monitoring email notifications and system alerts.</p>

                <?php
                $smtp_config = $current_config['smtp'] ?? [];
                $smtp_enabled = !empty($smtp_config['enabled']);
                $smtp_host = $smtp_config['host'] ?? '';
                $smtp_port = $smtp_config['port'] ?? 587;
                $smtp_encryption = $smtp_config['encryption'] ?? 'tls';
                $smtp_username = $smtp_config['username'] ?? '';
                $smtp_has_password = !empty($smtp_config['password']);
                $smtp_from_email = $smtp_config['from_email'] ?? '';
                $smtp_from_name = $smtp_config['from_name'] ?? 'WHP AI Monitor';
                ?>

                <form method="post">
                    <input type="hidden" name="action" value="update_smtp_settings">
                    <?php if (isset($_SESSION['csrf_token'])): ?>
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    <?php endif; ?>

                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" id="smtp_enabled" name="smtp_enabled" value="1" <?php echo $smtp_enabled ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="smtp_enabled">Enable Outbound Email</label>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="smtp_host" class="form-label">SMTP Host</label>
                            <input type="text" class="form-control" id="smtp_host" name="smtp_host" value="<?php echo htmlspecialchars($smtp_host); ?>" placeholder="smtp.example.com">
                        </div>
                        <div class="col-md-3">
                            <label for="smtp_port" class="form-label">Port</label>
                            <input type="number" class="form-control" id="smtp_port" name="smtp_port" value="<?php echo intval($smtp_port); ?>" min="1" max="65535">
                        </div>
                        <div class="col-md-3">
                            <label for="smtp_encryption" class="form-label">Encryption</label>
                            <select class="form-select" id="smtp_encryption" name="smtp_encryption">
                                <option value="tls" <?php echo $smtp_encryption === 'tls' ? 'selected' : ''; ?>>TLS (STARTTLS)</option>
                                <option value="ssl" <?php echo $smtp_encryption === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                <option value="none" <?php echo $smtp_encryption === 'none' ? 'selected' : ''; ?>>None</option>
                            </select>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="smtp_username" class="form-label">Username</label>
                            <input type="text" class="form-control" id="smtp_username" name="smtp_username" value="<?php echo htmlspecialchars($smtp_username); ?>" placeholder="user@example.com">
                        </div>
                        <div class="col-md-6">
                            <label for="smtp_password" class="form-label">Password</label>
                            <input type="password" class="form-control" id="smtp_password" name="smtp_password" value="<?php echo $smtp_has_password ? '********' : ''; ?>" placeholder="<?php echo $smtp_has_password ? 'Password saved (leave blank to keep)' : 'Enter password'; ?>">
                            <?php if ($smtp_has_password): ?>
                            <div class="form-text text-muted">Leave blank to keep existing password</div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="smtp_from_email" class="form-label">From Email</label>
                            <input type="email" class="form-control" id="smtp_from_email" name="smtp_from_email" value="<?php echo htmlspecialchars($smtp_from_email); ?>" placeholder="noreply@example.com">
                        </div>
                        <div class="col-md-6">
                            <label for="smtp_from_name" class="form-label">From Name</label>
                            <input type="text" class="form-control" id="smtp_from_name" name="smtp_from_name" value="<?php echo htmlspecialchars($smtp_from_name); ?>" placeholder="WHP AI Monitor">
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-save"></i> Save SMTP Settings
                    </button>
                </form>

                <?php if ($smtp_enabled && !empty($smtp_host)): ?>
                <hr>
                <form method="post" class="d-inline-flex align-items-end gap-2">
                    <input type="hidden" name="action" value="send_test_email">
                    <?php if (isset($_SESSION['csrf_token'])): ?>
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    <?php endif; ?>
                    <div>
                        <label for="test_email" class="form-label">Send Test Email</label>
                        <input type="email" class="form-control" id="test_email" name="test_email" placeholder="test@example.com" required>
                    </div>
                    <button type="submit" class="btn btn-outline-secondary">
                        <i class="fa fa-paper-plane"></i> Send Test
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php
// Bichon archival settings (root-only). Loads decrypted config to drive the
// form state; the api_token is never echoed back — the form shows '********'
// as a placeholder when one is already stored, and the save handler keeps the
// existing encrypted token unless a new value is submitted.
require_once('/docker/whp/web/libs/BichonClient.php');
$bichon_cfg     = BichonClient::loadConfig();
$bichon_enabled = !empty($bichon_cfg['enabled']);
$bichon_url     = $bichon_cfg['url'] ?? '';
$bichon_has_tok = !empty($bichon_cfg['api_token']);
$bichon_last_ok = $bichon_cfg['last_test_ok_at'] ?? null;
?>
<!-- Email Archival (Bichon) -->
<div class="row">
  <div class="col-md-12">
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="card-title mb-0"><i class="fa fa-archive"></i> Email Archival (Bichon)</h5>
      </div>
      <div class="card-body">
        <p class="text-muted small mb-3">Connect WHP to a self-hosted <a href="https://github.com/rustmailer/bichon" target="_blank" rel="noopener">Bichon</a> server so customers with the archival addon can push mailboxes into long-term archive.</p>
        <form method="POST" action="">
          <input type="hidden" name="action" value="update_bichon_settings">
          <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">

          <div class="form-check form-switch mb-3">
            <input type="checkbox" class="form-check-input" id="bichonEnabled" name="bichon_enabled" value="1" <?php echo $bichon_enabled ? 'checked' : ''; ?>>
            <label for="bichonEnabled" class="form-check-label">Enable Bichon archival integration</label>
          </div>

          <div class="mb-3">
            <label for="bichonUrl" class="form-label">Bichon URL</label>
            <input type="url" class="form-control" id="bichonUrl" name="bichon_url"
                   placeholder="https://archival.example.com"
                   value="<?php echo htmlspecialchars($bichon_url, ENT_QUOTES); ?>">
            <div class="form-text">
              Use HTTPS for production. <code>http://</code> is allowed for internal/test instances reachable only on a private network.
              <?php if (!empty($bichon_url) && stripos($bichon_url, 'http://') === 0): ?>
                <span class="text-warning"><i class="fa fa-exclamation-triangle"></i> Plain HTTP is in use &mdash; mailbox passwords and the bearer token will traverse the network unencrypted. Switch to HTTPS before going live.</span>
              <?php endif; ?>
            </div>
          </div>

          <div class="mb-3">
            <label for="bichonToken" class="form-label">API Token</label>
            <div class="input-group">
              <input type="password" class="form-control" id="bichonToken" name="bichon_api_token"
                     value="<?php echo $bichon_has_tok ? '********' : ''; ?>"
                     autocomplete="off">
              <button type="button" class="btn btn-outline-secondary" onclick="toggleBichonTokenView()" title="Show/hide token">
                <i class="fa fa-eye" id="bichonTokenEyeIcon"></i>
              </button>
            </div>
            <div class="form-text">
              <?php if ($bichon_last_ok): ?>
                Last verified: <?php echo htmlspecialchars($bichon_last_ok); ?>
              <?php else: ?>
                <span class="text-warning">Not yet verified.</span>
              <?php endif; ?>
            </div>
          </div>

          <div class="d-flex gap-2">
            <button type="button" class="btn btn-outline-primary" onclick="bichonTestConnection()">
              <i class="fa fa-plug"></i> Test Connection
            </button>
            <button type="submit" class="btn btn-primary">
              <i class="fa fa-save"></i> Save Settings
            </button>
            <span id="bichonTestResult" class="ms-2 align-self-center"></span>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<script>
function toggleBichonTokenView() {
  const input = document.getElementById('bichonToken');
  const icon  = document.getElementById('bichonTokenEyeIcon');
  if (input.type === 'password') { input.type = 'text';  icon.classList.replace('fa-eye','fa-eye-slash'); }
  else                            { input.type = 'password'; icon.classList.replace('fa-eye-slash','fa-eye'); }
}
function bichonRenderResult(iconClass, colorClass, message) {
  const result = document.getElementById('bichonTestResult');
  result.className = 'ms-2 align-self-center ' + colorClass;
  // Build DOM nodes manually so we don't pass server text through innerHTML.
  result.textContent = '';
  const i = document.createElement('i');
  i.className = 'fa ' + iconClass;
  result.appendChild(i);
  result.appendChild(document.createTextNode(' ' + message));
}
async function bichonTestConnection() {
  bichonRenderResult('fa-spinner fa-spin', 'text-muted', 'Testing…');
  const url   = document.getElementById('bichonUrl').value;
  const token = document.getElementById('bichonToken').value;
  const fd = new FormData();
  fd.append('csrf_token', '<?php echo get_csrf_token(); ?>');
  if (url)   fd.append('url', url);
  if (token && token !== '********') fd.append('token', token);
  try {
    const r = await fetch('/api/bichon-test.php?action=test', { method: 'POST', body: fd });
    const j = await r.json();
    if (j.status === 'success') {
      bichonRenderResult('fa-check', 'text-success', j.message || 'Connected');
    } else {
      bichonRenderResult('fa-times', 'text-danger', j.message || 'Failed');
    }
  } catch (e) {
    bichonRenderResult('fa-times', 'text-danger', e.message);
  }
}
</script>
