<?php
session_start();
date_default_timezone_set('Africa/Lagos');
require __DIR__ . '/../config.php';
require __DIR__ . '/includes/auth_init.php';

if (!$isAdmin) {
    $_SESSION['flash_error'] = "You don't have permission to test email settings.";
    header("Location: dashboard.php");
    exit;
}

// Release the session lock on plain page views; the POST branches below still
// need to write flash data, so they keep the session open for themselves. This
// matters a lot on this particular page since sending a test email over SMTP
// can take several seconds -- without this, that request would block every
// other tab/page for this user until the SMTP call finishes.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    session_write_close();
}

$settings = $conn->query("SELECT * FROM email_settings ORDER BY id DESC LIMIT 1")->fetch_assoc();

$portTestResults = [];
$sendResult = null;
$sendTranscript = '';

// ---------------------------------------------------------------------
// Raw TCP connectivity test -- bypasses PHPMailer entirely, so we can
// tell "host blocks this port" apart from "PHPMailer/credentials issue".
// ---------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_ports'])) {
    $host = $settings['smtp_host'] ?? 'sandbox.smtp.mailtrap.io';
    $portsToTest = [25, 465, 587, 2525];
    foreach ($portsToTest as $port) {
        $start = microtime(true);
        $errno = 0;
        $errstr = '';
        $conn2 = @fsockopen($host, $port, $errno, $errstr, 5);
        $elapsed = round((microtime(true) - $start) * 1000);
        if ($conn2) {
            fclose($conn2);
            $portTestResults[$port] = ['ok' => true, 'message' => "Connected in {$elapsed}ms"];
        } else {
            $portTestResults[$port] = ['ok' => false, 'message' => "errno $errno: $errstr ({$elapsed}ms)"];
        }
    }
}

// ---------------------------------------------------------------------
// Real send test, with full SMTP debug transcript captured to display.
// ---------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_test'])) {
    $testEmail = trim($_POST['test_email'] ?? '');

    require __DIR__ . '/../vendor/autoload.php';
    require __DIR__ . '/includes/helpers.php';

    if (empty($testEmail)) {
        $sendResult = ['success' => false, 'error' => 'Enter a recipient email address.'];
    } elseif (empty($settings)) {
        $sendResult = ['success' => false, 'error' => 'No email settings saved yet -- go to Email Settings first.'];
    } else {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        $debugOutput = [];
        try {
            $mail->isSMTP();
            $mail->Host = $settings['smtp_host'];
            $mail->SMTPAuth = true;
            $mail->Username = $settings['smtp_username'];
            $mail->Password = $settings['smtp_password'];
            $mail->SMTPSecure = $settings['encryption'] === 'ssl' ? PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS : PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = (int) $settings['smtp_port'];
            $mail->Timeout = 15;

            $mail->CharSet = PHPMailer\PHPMailer\PHPMailer::CHARSET_UTF8;
            $mail->Encoding = 'base64';

            $mail->SMTPDebug = 2; // full conversation transcript
            $mail->Debugoutput = function ($str, $level) use (&$debugOutput) {
                $debugOutput[] = trim($str);
            };

            $mail->setFrom($settings['from_email'], $settings['from_name']);
            $mail->addAddress($testEmail);
            $mail->isHTML(true);
            $mail->Subject = 'Payroll Module Test Email';
            $mail->Body = '<p>This is a test email from your HR Payroll module. If you received this, your Mailtrap SMTP settings are working correctly.</p>';
            $mail->AltBody = 'This is a test email from your HR Payroll module.';

            $mail->send();
            $sendResult = ['success' => true, 'error' => null];
        } catch (Exception $e) {
            $sendResult = ['success' => false, 'error' => $mail->ErrorInfo ?: $e->getMessage()];
        }
        $sendTranscript = implode("\n", $debugOutput);
    }
}

$pageTitle = 'Email Diagnostics';
$pageSubtitle = 'Payroll Module';
require __DIR__ . '/includes/layout_header.php';
?>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Current Settings</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-3">From <a href="email_settings.php" class="text-indigo-700 underline">Email Settings</a>.</p>
    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
        <div><span class="font-black text-slate-400 uppercase text-[9px] block">Host</span><?= h($settings['smtp_host'] ?? 'not set'); ?></div>
        <div><span class="font-black text-slate-400 uppercase text-[9px] block">Port</span><?= h($settings['smtp_port'] ?? 'not set'); ?></div>
        <div><span class="font-black text-slate-400 uppercase text-[9px] block">Encryption</span><?= h($settings['encryption'] ?? 'not set'); ?></div>
        <div><span class="font-black text-slate-400 uppercase text-[9px] block">Username Set</span><?= !empty($settings['smtp_username']) ? 'Yes' : 'No'; ?></div>
    </div>
</div>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Step 1: Raw Connectivity Test</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-3">
        Tests whether your server can even open a TCP connection to <?= h($settings['smtp_host'] ?? 'the SMTP host'); ?> on common Mailtrap ports (25, 465, 587, 2525) --
        bypassing PHPMailer entirely. If every port fails with "Connection refused", your host's firewall is blocking outbound SMTP and no amount of credential-fixing will help; contact your hosting provider to whitelist one of these ports for outbound connections.
    </p>
    <form method="POST">
        <button type="submit" name="test_ports" class="bg-slate-900 hover:bg-slate-800 text-white text-xs font-black uppercase px-5 py-2.5 rounded-lg transition active:scale-95 border border-slate-950">Test Ports Now</button>
    </form>

    <?php if (!empty($portTestResults)): ?>
    <div class="mt-4 space-y-2">
        <?php foreach ($portTestResults as $port => $result): ?>
        <div class="flex items-center justify-between border border-slate-200 rounded-lg px-4 py-2 text-xs">
            <span class="font-bold">Port <?= $port; ?></span>
            <span class="<?= $result['ok'] ? 'text-emerald-700' : 'text-rose-700'; ?> font-semibold"><?= h($result['message']); ?></span>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs">
    <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight mb-1">Step 2: Send a Real Test Email</h3>
    <p class="text-[11px] text-slate-500 font-semibold mb-3">Sends one actual email through PHPMailer with full debug output, so we can see exactly where it succeeds or fails.</p>
    <form method="POST" class="flex flex-col sm:flex-row gap-3">
        <input type="email" name="test_email" required placeholder="your@email.com" value="<?= h($_POST['test_email'] ?? ''); ?>"
               class="flex-1 text-sm border border-slate-200 rounded-lg p-3">
        <button type="submit" name="send_test" class="bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-black uppercase px-5 py-2.5 rounded-lg transition active:scale-95 border border-emerald-700">Send Test Email</button>
    </form>

    <?php if ($sendResult): ?>
    <div class="mt-4 p-3 rounded-lg text-xs font-semibold <?= $sendResult['success'] ? 'bg-emerald-50 text-emerald-800 border border-emerald-300' : 'bg-rose-50 text-rose-800 border border-rose-300'; ?>">
        <?= $sendResult['success'] ? 'Sent successfully! Check the recipient inbox (or Mailtrap sandbox inbox).' : h($sendResult['error']); ?>
    </div>
    <?php endif; ?>

    <?php if ($sendTranscript): ?>
    <div class="mt-3">
        <p class="text-[10px] font-black text-slate-400 uppercase mb-1">Full SMTP Transcript</p>
        <pre class="bg-slate-900 text-emerald-400 text-[10px] p-4 rounded-lg overflow-x-auto whitespace-pre-wrap"><?= h($sendTranscript); ?></pre>
    </div>
    <?php endif; ?>
</div>

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