<?php
$whitelistFile = __DIR__ . '/whitelist.json';
$clientIP = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
$whitelist = file_exists($whitelistFile) ? json_decode(file_get_contents($whitelistFile), true) : [];

if (!is_array($whitelist) || !in_array($clientIP, $whitelist, true)) {
    http_response_code(403);
    exit('Access Denied');
}

require __DIR__ . '/mledak/Exception.php';
require __DIR__ . '/mledak/PHPMailer.php';
require __DIR__ . '/mledak/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$configPath = __DIR__ . '/config.ini';
if (!file_exists($configPath)) {
    die('config.ini not found');
}
$config = parse_ini_file($configPath, true);

$internalFrom  = $config['email']['from_email'] ?? null;
$recipientEmail = $config['result']['email'] ?? null;
$smtpExternal   = $config['smtp_external'] ?? null;

$result = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $testRecipient = $_POST['test_email'] ?? $recipientEmail;

    if (!filter_var($testRecipient, FILTER_VALIDATE_EMAIL)) {
        $result[] = ['type' => 'error', 'msg' => 'Invalid test email address.'];
    } else {
        // --- Test Internal (cPanel isMail) ---
        try {
            $mail = new PHPMailer(true);
            $mail->isMail();
            $mail->setFrom($internalFrom, 'SMTP Test');
            $mail->addAddress($testRecipient);
            $mail->isHTML(true);
            $mail->Subject = '[INTERNAL] SMTP Test - ' . date('Y-m-d H:i:s');
            $mail->Body    = '<h3>Internal cPanel Mail Test</h3><p>If you receive this, internal email (isMail) is working.</p>';
            $mail->send();
            $result[] = ['type' => 'success', 'msg' => "INTERNAL OK — Sent via cPanel isMail() from <b>{$internalFrom}</b> to <b>{$testRecipient}</b>"];
        } catch (Exception $e) {
            $result[] = ['type' => 'danger', 'msg' => 'INTERNAL FAIL — ' . $e->getMessage()];
        }

        // --- Test External SMTP ---
        if ($smtpExternal) {
            try {
                $mail2 = new PHPMailer(true);
                $mail2->SMTPDebug = 2;
                $mail2->Debugoutput = function($str, $level) use (&$smtpLog) {
                    $smtpLog .= htmlspecialchars($str);
                };
                $smtpLog = '';

                $mail2->isSMTP();
                $mail2->Host       = $smtpExternal['host'] ?? 'localhost';
                $mail2->SMTPAuth   = true;
                $mail2->Username   = $smtpExternal['username'] ?? '';
                $mail2->Password   = $smtpExternal['password'] ?? '';
                $mail2->Port       = (int)($smtpExternal['port'] ?? 587);

                $enc = strtolower($smtpExternal['encryption'] ?? 'tls');
                if ($enc === 'tls') {
                    $mail2->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                } elseif ($enc === 'ssl') {
                    $mail2->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                }

                $mail2->SMTPOptions = [
                    'ssl' => [
                        'verify_peer'       => false,
                        'verify_peer_name'  => false,
                        'allow_self_signed' => true,
                    ],
                ];

                $extFrom = $smtpExternal['from_email'] ?? $smtpExternal['username'] ?? 'no-reply@localhost';

                $mail2->setFrom($extFrom, 'SMTP Test');
                $mail2->addAddress($testRecipient);
                $mail2->isHTML(true);
                $mail2->Subject = '[EXTERNAL] SMTP Test - ' . date('Y-m-d H:i:s');
                $mail2->Body    = '<h3>External SMTP Test</h3><p>If you receive this, external SMTP is working.</p>';
                $mail2->send();
                $result[] = ['type' => 'success', 'msg' => "EXTERNAL OK — Sent via SMTP ({$smtpExternal['host']}:{$smtpExternal['port']}) from <b>{$extFrom}</b> to <b>{$testRecipient}</b>"];
                if ($smtpLog) {
                    $result[] = ['type' => 'warning', 'msg' => '<pre style="font-size:11px;max-height:300px;overflow:auto;white-space:pre-wrap;">' . $smtpLog . '</pre>'];
                }
            } catch (Exception $e) {
                $result[] = ['type' => 'danger', 'msg' => 'EXTERNAL FAIL — ' . $e->getMessage()];
                if ($smtpLog) {
                    $result[] = ['type' => 'warning', 'msg' => '<pre style="font-size:11px;max-height:300px;overflow:auto;white-space:pre-wrap;">' . $smtpLog . '</pre>'];
                }
            }
        } else {
            $result[] = ['type' => 'warning', 'msg' => 'EXTERNAL SKIPPED — No [smtp_external] config found in config.ini'];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMTP Test</title>
    <style>
        :root {
            --bg: #0f111a; --card: rgba(20, 22, 36, 0.9);
            --success: #55efc4; --danger: #ff7675; --warning: #ffeaa7;
            --text: #fff; --accent: #a29bfe; --border: rgba(255,255,255,0.08);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            background: var(--bg); color: var(--text);
            font-family: 'Inter', system-ui, sans-serif;
            display: flex; justify-content: center; align-items: center;
            min-height: 100vh;
        }
        .container {
            background: var(--card); border: 1px solid var(--border);
            border-radius: 20px; padding: 40px; width: 100%; max-width: 640px;
        }
        h2 { margin-bottom: 8px; }
        h2 span { color: var(--accent); }
        .sub { color: #aaa; font-size: 13px; margin-bottom: 24px; }
        label { display: block; font-size: 12px; font-weight: 700; margin-bottom: 6px; color: #aaa; }
        input[type="email"] {
            width: 100%; padding: 12px 16px; border-radius: 10px;
            border: 1px solid var(--border); background: rgba(255,255,255,0.05);
            color: #fff; font-size: 14px; margin-bottom: 20px; outline: none;
        }
        input[type="email"]:focus { border-color: var(--accent); }
        .btn {
            width: 100%; padding: 14px; border: none; border-radius: 12px;
            background: var(--accent); color: #000; font-weight: 700;
            font-size: 14px; cursor: pointer; transition: 0.2s;
        }
        .btn:hover { opacity: 0.85; }
        .result { margin-top: 24px; }
        .alert {
            padding: 14px 18px; border-radius: 10px; margin-bottom: 10px;
            font-size: 13px; line-height: 1.5;
        }
        .alert-success { background: rgba(85,239,196,0.1); border: 1px solid var(--success); color: var(--success); }
        .alert-danger  { background: rgba(255,118,117,0.1); border: 1px solid var(--danger); color: var(--danger); }
        .alert-warning { background: rgba(255,234,167,0.1); border: 1px solid var(--warning); color: var(--warning); }
        .alert-error   { background: rgba(255,118,117,0.1); border: 1px solid var(--danger); color: var(--danger); }
        .back-link { display: inline-block; margin-top: 20px; color: var(--accent); font-size: 13px; text-decoration: none; }
        .back-link:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div class="container">
        <h2>SMTP <span>Test</span></h2>
        <p class="sub">Test internal cPanel mail + external SMTP fallback</p>

        <form method="POST">
            <label>Test Recipient Email</label>
            <input type="email" name="test_email" value="<?= htmlspecialchars($recipientEmail ?? '') ?>" placeholder="email@example.com" required>
            <button type="submit" class="btn">Send Test Emails</button>
        </form>

        <?php if (!empty($result)): ?>
        <div class="result">
            <?php foreach ($result as $r): ?>
            <div class="alert alert-<?= $r['type'] ?>"><?= $r['msg'] ?></div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <a href="dash.php" class="back-link">&larr; Back to Dashboard</a>
    </div>
</body>
</html>
