<?php
// /admin/test_mail.php
declare(strict_types=1);

session_start();

$config = require __DIR__ . '/../lib/config.php';
require_once __DIR__ . '/../lib/mailer.php';

$base    = rtrim($config['base_url'] ?? '', '/');
$mailCfg = $config['mail'] ?? [];
$smtp    = $mailCfg['smtp'] ?? [];

$allow = ($config['env'] ?? 'prod') !== 'prod' || ($_GET['ok'] ?? '') === 'yes';
if (!$allow) {
  http_response_code(403);
  echo "Forbidden. Add ?ok=yes to run in production, then delete this file when done.";
  exit;
}

$to = trim($_GET['to'] ?? ($mailCfg['from_email'] ?? ''));
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
  $to = $mailCfg['from_email'] ?? '';
}

$subject = 'MPMS/Towlens SMTP Test';
$html    = '<p>This is a test email from <b>/admin/test_mail.php</b>.</p><p>If you received this, SMTP and From are working.</p>';

[$ok, $err] = mpms_mail_send($config, $to, $subject, $html);

// Helper: tail log
$logFile = __DIR__ . '/../logs/mail.log';
@mkdir(dirname($logFile), 0775, true);
if (!is_file($logFile)) @touch($logFile);

function tailLog(string $file, int $lines = 200): string {
  if (!is_file($file)) return "(log file not found)";
  $fp = fopen($file, 'rb');
  if (!$fp) return "(cannot open log)";
  $buffer = '';
  $chunk  = 4096;
  fseek($fp, 0, SEEK_END);
  $pos = ftell($fp);
  $lineCount = 0;
  while ($pos > 0 && $lineCount <= $lines) {
    $read = ($pos >= $chunk) ? $chunk : $pos;
    $pos -= $read;
    fseek($fp, $pos);
    $buffer = fread($fp, $read) . $buffer;
    $lineCount = substr_count($buffer, "\n");
  }
  fclose($fp);
  $arr = explode("\n", $buffer);
  return implode("\n", array_slice($arr, -$lines));
}

function mask(string $s): string {
  if ($s === '') return '';
  if (strpos($s, '@') !== false) {
    [$u,$d] = explode('@',$s,2);
    $uMask = strlen($u) > 2 ? substr($u,0,1) . str_repeat('•', max(1, strlen($u)-2)) . substr($u,-1) : str_repeat('•', strlen($u));
    return $uMask . '@' . $d;
  }
  return substr($s,0,1) . str_repeat('•', max(1, strlen($s)-2)) . substr($s,-1);
}

header('Content-Type: text/html; charset=utf-8');
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SMTP Test</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{font:14px/1.5 system-ui,Segoe UI,Arial,sans-serif;margin:20px;color:#1f2937}
    .ok{color:#065f46;background:#ecfdf5;border:1px solid #a7f3d0;padding:10px;border-radius:6px}
    .err{color:#991b1b;background:#fef2f2;border:1px solid #fecaca;padding:10px;border-radius:6px}
    code,pre{background:#f3f4f6;border:1px solid #e5e7eb;border-radius:6px;padding:10px;display:block;overflow:auto;max-height:50vh}
    table{border-collapse:collapse}
    td{padding:6px 10px;border-bottom:1px solid #e5e7eb;vertical-align:top}
    .small{color:#6b7280;font-size:12px}
    .box{border:1px solid #e5e7eb;border-radius:8px;padding:12px;margin-top:14px}
    input[type="email"]{padding:8px;border:1px solid #cbd5e1;border-radius:6px;min-width:260px}
    button{padding:8px 12px;border:1px solid #93c5fd;background:#dbeafe;border-radius:6px;cursor:pointer}
  </style>
</head>
<body>
  <h1>SMTP Test</h1>

  <form method="get" action="">
    <p>
      <label>Send test to:&nbsp;
        <input type="email" name="to" value="<?= htmlspecialchars($to) ?>" required>
      </label>
      <input type="hidden" name="ok" value="yes">
      <button type="submit">Send</button>
    </p>
  </form>

  <?php if ($ok): ?>
    <div class="ok"><strong>Success:</strong> Test email sent to <b><?= htmlspecialchars($to) ?></b>.</div>
  <?php else: ?>
    <div class="err"><strong>Failed:</strong> <?= htmlspecialchars($err ?? 'Unknown error') ?></div>
  <?php endif; ?>

  <div class="box">
    <h3>Using config</h3>
    <table>
      <tr><td>From email</td><td><?= htmlspecialchars($mailCfg['from_email'] ?? '') ?></td></tr>
      <tr><td>From name</td><td><?= htmlspecialchars($mailCfg['from_name'] ?? '') ?></td></tr>
      <tr><td>BCC</td><td><?= htmlspecialchars($mailCfg['bcc'] ?? '') ?></td></tr>
      <tr><td>SMTP host</td><td><?= htmlspecialchars($smtp['host'] ?? '') ?></td></tr>
      <tr><td>SMTP port</td><td><?= htmlspecialchars((string)($smtp['port'] ?? '')) ?></td></tr>
      <tr><td>SMTP secure</td><td><?= htmlspecialchars($smtp['secure'] ?? '') ?></td></tr>
      <tr><td>SMTP user</td><td><?= htmlspecialchars(mask((string)($smtp['user'] ?? ''))) ?></td></tr>
      <tr><td>SMTP pass</td><td><?= htmlspecialchars(mask((string)($smtp['pass'] ?? ''))) ?></td></tr>
      <tr><td>Env</td><td><?= htmlspecialchars($config['env'] ?? '') ?></td></tr>
      <tr><td>Log file</td><td><?= htmlspecialchars($logFile) ?></td></tr>
    </table>
    <p class="small">Tip: Some providers require a specific host like <code>smtp.yourhost.com</code>, not a bare domain.</p>
  </div>

  <div class="box">
    <h3>Mail log (last 200 lines)</h3>
    <pre><?= htmlspecialchars(tailLog($logFile, 200)) ?></pre>
  </div>
</body>
</html>
