<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Controller;

final class AdminSmtpDiagnoseController extends Controller
{
    public function index(): void
    {
        require_login();
        if (function_exists('is_admin') && !is_admin()) { http_response_code(403); echo "Forbidden"; return; }

        $cfg = require __DIR__ . '/../../config/mail.php';
        $host = (string)$cfg['smtp_host'];
        $port = (int)$cfg['smtp_port'];
        $secure = (string)$cfg['smtp_secure'];

        $out = [];
        $remote = ($secure === 'ssl') ? "ssl://{$host}:{$port}" : "{$host}:{$port}";
        $out[] = "Connecting to: $remote";

        $fp = @stream_socket_client($remote, $errno, $errstr, 15, STREAM_CLIENT_CONNECT);
        if (!$fp) {
            $out[] = "CONNECT FAILED: $errstr ($errno)";
            $this->view('admin/smtp_diagnose/index', ['out'=>implode("\n",$out)]);
            return;
        }

        stream_set_timeout($fp, 15);
        $banner = fgets($fp, 515);
        $out[] = "BANNER: " . trim((string)$banner);

        fwrite($fp, "EHLO easychair.local\r\n");
        $resp = '';
        while (!feof($fp)) {
            $line = fgets($fp, 515);
            if ($line === false) break;
            $resp .= $line;
            if (strlen($line) >= 4 && $line[3] === ' ') break;
        }
        $out[] = "EHLO RESP:\n" . trim($resp);

        fwrite($fp, "QUIT\r\n");
        fclose($fp);

        $this->view('admin/smtp_diagnose/index', ['out'=>implode("\n",$out)]);
    }
}
