<?php
/**
 * Temporary diagnostic for the contact form.
 *
 * Visit:  https://newnorfolkroofingltd.co.uk/mail-test.php?key=nnr-diagnose
 *
 * It never prints the password — only whether one is set.
 * DELETE THIS FILE once the form is working.
 */

header('Content-Type: text/plain; charset=utf-8');
ini_set('display_errors', '1');
error_reporting(E_ALL);

if (($_GET['key'] ?? '') !== 'nnr-diagnose') {
    http_response_code(404);
    echo "Not found.\n";
    exit;
}

$pass = static function (bool $ok, string $label, string $extra = '') {
    echo ($ok ? '  OK   ' : ' FAIL  ') . $label . ($extra !== '' ? ' — ' . $extra : '') . "\n";
    return $ok;
};

echo "NEW NORFOLK ROOFING — MAIL DIAGNOSTIC\n";
echo str_repeat('=', 52) . "\n\n";

echo "1. PHP\n";
$pass(true, 'Version', PHP_VERSION);
$pass(PHP_VERSION_ID >= 70400, 'PHP 7.4 or newer', PHP_VERSION_ID >= 70400 ? 'fine' : 'TOO OLD — raise it in cPanel');
$pass(extension_loaded('openssl'), 'openssl extension', extension_loaded('openssl') ? 'present' : 'MISSING — required for port 465');
$pass(function_exists('fsockopen'), 'fsockopen available');
echo "\n";

echo "2. Files\n";
foreach (['lib/PHPMailer/PHPMailer.php', 'lib/PHPMailer/SMTP.php', 'lib/PHPMailer/Exception.php'] as $f) {
    $pass(is_readable(__DIR__ . '/' . $f), $f);
}
$configPath = __DIR__ . '/mail-config.php';
$hasConfig = $pass(is_readable($configPath), 'mail-config.php', is_readable($configPath) ? 'found' : 'MISSING — copy mail-config.sample.php to mail-config.php');
echo "\n";

if (!$hasConfig) {
    echo "Stopping: create mail-config.php first.\n";
    exit;
}

$config = require $configPath;

echo "3. Config values\n";
$pass(!empty($config['smtp_host']), 'smtp_host', (string) ($config['smtp_host'] ?? ''));
$pass(!empty($config['smtp_port']), 'smtp_port', (string) ($config['smtp_port'] ?? ''));
$pass(!empty($config['smtp_username']), 'smtp_username', (string) ($config['smtp_username'] ?? ''));
$rawPassword = (string) ($config['smtp_password'] ?? '');
$pass($rawPassword !== '', 'smtp_password', $rawPassword !== ''
    ? 'set (' . strlen($rawPassword) . ' characters)'
    : 'EMPTY — add the mailbox password');

// Stray whitespace from copy/paste is the single most common cause of a 535.
$pass(
    $rawPassword === trim($rawPassword),
    'password has no stray whitespace',
    $rawPassword === trim($rawPassword)
        ? 'clean'
        : 'HAS LEADING/TRAILING WHITESPACE — remove it (' . strlen(trim($rawPassword)) . ' chars once trimmed)'
);

// A backslash in a single-quoted PHP string stays literal and will not match.
$pass(
    strpos($rawPassword, '\\') === false,
    'password has no backslash',
    strpos($rawPassword, '\\') === false ? 'clean' : 'CONTAINS A BACKSLASH — check it is escaped correctly'
);

$pass(!empty($config['to_email']), 'to_email', (string) ($config['to_email'] ?? ''));
echo "\n";

echo "4. Network\n";
$host = (string) $config['smtp_host'];
$port = (int) $config['smtp_port'];
$ip = gethostbyname($host);
$pass($ip !== $host, 'DNS resolves ' . $host, $ip !== $host ? $ip : 'COULD NOT RESOLVE');

$errno = 0;
$errstr = '';
$sock = @fsockopen(($port === 465 ? 'ssl://' : '') . $host, $port, $errno, $errstr, 12);
if ($sock) {
    $banner = trim((string) fgets($sock, 512));
    $pass(true, "TCP/SSL connect to {$host}:{$port}", $banner !== '' ? $banner : 'connected');
    fclose($sock);
} else {
    $pass(false, "TCP/SSL connect to {$host}:{$port}", "[{$errno}] {$errstr} — likely blocked by the host's firewall");
}
echo "\n";

echo "5. SMTP login test\n";
require __DIR__ . '/lib/PHPMailer/Exception.php';
require __DIR__ . '/lib/PHPMailer/PHPMailer.php';
require __DIR__ . '/lib/PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer(true);
$log = '';
try {
    $mail->isSMTP();
    $mail->Host = $host;
    $mail->Port = $port;
    $mail->SMTPAuth = true;
    $mail->Username = $config['smtp_username'];
    $mail->Password = $config['smtp_password'];
    $mail->SMTPSecure = ($config['smtp_secure'] ?? 'ssl') === 'tls'
        ? PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS
        : PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
    $mail->Timeout = 15;
    $mail->SMTPDebug = PHPMailer\PHPMailer\SMTP::DEBUG_CONNECTION;
    $mail->Debugoutput = static function ($str) use (&$log) {
        $log .= '   | ' . rtrim($str) . "\n";
    };

    if ($mail->smtpConnect()) {
        $pass(true, 'Authenticated successfully');
        $mail->smtpClose();
        echo "\n   The SMTP details are correct. If the form still fails, the problem\n";
        echo "   is in mail.php — check the browser console for the 'detail' value.\n";
    } else {
        $pass(false, 'Authentication', $mail->ErrorInfo);
    }
} catch (Throwable $e) {
    $pass(false, 'Authentication', $e->getMessage());
}

echo "\n6. SMTP conversation\n" . ($log !== '' ? $log : "   (none captured)\n");

echo "\n7. Fallback: local sendmail\n";
$sendmailPath = ini_get('sendmail_path');
$pass($sendmailPath !== '' && $sendmailPath !== false, 'sendmail_path', $sendmailPath ?: 'not set');
$binary = trim(explode(' ', trim((string) $sendmailPath))[0]);
$pass($binary !== '' && is_executable($binary), 'sendmail binary', $binary !== '' ? $binary : 'unknown');
echo "\n   If SMTP auth cannot be fixed, set 'transport' => 'sendmail' in\n";
echo "   mail-config.php. Same-server delivery, no password required.\n";

echo "\nDone. DELETE mail-test.php when finished.\n";
