<?php
require_once __DIR__ . '/config/config.php';
require_role(['admin']);

$result = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $to = trim($_POST['to'] ?? '');
    if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
        $result = ['ok' => false, 'msg' => 'Please enter a valid email address.'];
    } else {
        $ok = send_email($to, APP_NAME . ' - Test Email',
            '<p>This is a test email from the Hotel Inventory Management System.</p>' .
            '<p>Driver: <strong>' . e(MAIL_DRIVER) . '</strong>' .
            (MAIL_DRIVER === 'smtp' ? ' (' . e(SMTP_PROFILE) . ')' : '') . '</p>' .
            '<p>Sent at ' . date('Y-m-d H:i:s') . '</p>');
        $result = ['ok' => $ok, 'msg' => $ok ? 'Sent successfully. Check the inbox (or Mailtrap, if that\'s your active profile).'
                                              : 'Failed to send. Check config/mail_config.php and your PHP error log for details.'];
    }
}

$pageTitle = 'Test Email Configuration';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">Test Email Configuration</h1>
<p class="text-slate-500 text-sm mb-6">
  Current driver: <span class="font-semibold"><?= e(MAIL_DRIVER) ?></span>
  <?= MAIL_DRIVER === 'smtp' ? ' · Profile: <span class="font-semibold">' . e(SMTP_PROFILE) . '</span>' : '' ?>
  (change in <code>config/mail_config.php</code>)
</p>

<?php if ($result): ?>
  <div class="mb-4 max-w-md border <?= $result['ok'] ? 'bg-emerald-50 border-emerald-200 text-emerald-700' : 'bg-red-50 border-red-200 text-red-700' ?> px-4 py-2.5 rounded-lg text-sm">
    <?= e($result['msg']) ?>
  </div>
<?php endif; ?>

<form method="POST" class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 max-w-md space-y-4">
  <div>
    <label class="text-sm font-medium block mb-1">Send test email to</label>
    <input type="email" name="to" required placeholder="you@example.com" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
  </div>
  <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">Send Test Email</button>
</form>
<?php include __DIR__ . '/includes/footer.php'; ?>
