<?php

if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    session_start();
}

if (file_exists(__DIR__ . '/mail_config.php')) {
    require_once __DIR__ . '/mail_config.php';
}

// ============================================================
// Socket SMTP Client with Enhanced SSL/TLS Stream Support
// ============================================================
class SimpleSmtpMailer
{
    private $host, $port, $username, $password, $encryption;
    public $lastError = '';

    public function __construct($host, $port, $username, $password, $encryption = 'tls') {
        $this->host       = $host;
        $this->port       = (int)$port;
        $this->username   = $username;
        $this->password   = $password;
        $this->encryption = strtolower($encryption);
    }

    public function send($fromEmail, $fromName, $toEmail, $subject, $htmlBody) {
        $transport = ($this->encryption === 'ssl' || $this->port === 465) ? 'ssl://' : 'tcp://';
        
        // Disable strict peer verification on raw sockets to prevent TLS stream drops
        $context = stream_context_create([
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true,
                'crypto_method'     => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT
            ]
        ]);

        $sock = @stream_socket_client(
            $transport . $this->host . ':' . $this->port, 
            $errno, 
            $errstr, 
            15, 
            STREAM_CLIENT_CONNECT, 
            $context
        );

        if (!$sock) { 
            $this->lastError = "Connection failed to {$this->host}:{$this->port} -> ($errno) $errstr"; 
            return false; 
        }

        stream_set_timeout($sock, 15);

        $read = function () use ($sock) {
            $data = '';
            while ($line = fgets($sock, 515)) {
                $data .= $line;
                if (substr($line, 3, 1) === ' ') break;
            }
            return $data;
        };
        $write = function ($cmd) use ($sock) { fwrite($sock, $cmd . "\r\n"); };

        $banner = $read(); // Read banner
        if (substr($banner, 0, 3) !== '220') {
            $this->lastError = "Server banner refused: $banner";
            fclose($sock);
            return false;
        }

        $appHost = defined('APP_URL') ? (parse_url(APP_URL, PHP_URL_HOST) ?: 'localhost') : 'localhost';
        $write('EHLO ' . $appHost);
        $read();

        if ($this->encryption === 'tls' && $this->port !== 465) {
            $write('STARTTLS');
            $resp = $read();
            if (substr($resp, 0, 3) !== '220') { 
                $this->lastError = "STARTTLS refused: $resp"; 
                fclose($sock); 
                return false; 
            }

            // Enable TLS Encryption
            $crypto = @stream_socket_enable_crypto(
                $sock, 
                true, 
                STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT | STREAM_CRYPTO_METHOD_TLS_CLIENT
            );

            if (!$crypto) {
                $this->lastError = 'TLS crypto negotiation failed on socket stream'; 
                fclose($sock); 
                return false;
            }

            $write('EHLO ' . $appHost);
            $read();
        }

        if ($this->username) {
            $write('AUTH LOGIN');
            $read();
            $write(base64_encode($this->username));
            $read();
            $write(base64_encode($this->password));
            $resp = $read();
            if (substr($resp, 0, 3) !== '235') { 
                $this->lastError = "SMTP Auth Failed: $resp (Check Username/Password)"; 
                fclose($sock); 
                return false; 
            }
        }

        $write("MAIL FROM:<$fromEmail>");
        $resp = $read();
        if (substr($resp, 0, 3) !== '250') { 
            $this->lastError = "MAIL FROM Rejected: $resp (Check if $fromEmail domain is verified in Mailtrap)"; 
            fclose($sock); 
            return false; 
        }

        $write("RCPT TO:<$toEmail>");
        $resp = $read();
        if (substr($resp, 0, 1) !== '2') { 
            $this->lastError = "RCPT TO Rejected: $resp"; 
            fclose($sock); 
            return false; 
        }

        $write('DATA');
        $resp = $read();
        if (substr($resp, 0, 3) !== '354') {
            $this->lastError = "DATA Command Rejected: $resp";
            fclose($sock);
            return false;
        }

        $headers  = "From: $fromName <$fromEmail>\r\n";
        $headers .= "To: <$toEmail>\r\n";
        $headers .= "Subject: $subject\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        $headers .= "Date: " . date('r') . "\r\n";

        $escapedBody = preg_replace('/^\./m', '..', $htmlBody);

        $write($headers . "\r\n" . $escapedBody . "\r\n.");
        $resp = $read();
        if (substr($resp, 0, 3) !== '250') { 
            $this->lastError = "Message Rejected by Server: $resp"; 
            fclose($sock); 
            return false; 
        }

        $write('QUIT');
        fclose($sock);
        return true;
    }
}

// Global Procedural Function
if (!function_exists('send_email')) {
    function send_email($toEmail, $subject, $htmlBody, $fromAddress = null, $fromName = null) {
        $fromEmail  = $fromAddress ?: (defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'no-reply@yenagoahotel.com');
        $senderName = $fromName ?: (defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : 'Best Western HR Engine');

        if (defined('MAIL_DRIVER') && MAIL_DRIVER === 'php_mail') {
            $headers  = "From: $senderName <$fromEmail>\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
            return @mail($toEmail, $subject, $htmlBody, $headers);
        }

        // Determine profile
        if (defined('SMTP_PROFILE') && SMTP_PROFILE === 'production') {
            $host       = SMTP_HOST;
            $port       = SMTP_PORT;
            $username   = SMTP_USERNAME;
            $password   = SMTP_PASSWORD;
            $encryption = SMTP_ENCRYPTION;
        } else {
            $host       = defined('MAILTRAP_HOST') ? MAILTRAP_HOST : 'live.smtp.mailtrap.io';
            $port       = defined('MAILTRAP_PORT') ? MAILTRAP_PORT : 2525;
            $username   = defined('MAILTRAP_USERNAME') ? MAILTRAP_USERNAME : 'api';
            $password   = defined('MAILTRAP_PASSWORD') ? MAILTRAP_PASSWORD : '';
            $encryption = defined('MAILTRAP_ENCRYPTION') ? MAILTRAP_ENCRYPTION : 'tls';
        }

        $mailer = new SimpleSmtpMailer($host, $port, $username, $password, $encryption);
        $result = $mailer->send($fromEmail, $senderName, $toEmail, $subject, $htmlBody);
        
        if (!$result) {
            error_log("SimpleSmtpMailer Failure: " . $mailer->lastError);
            $_SESSION['mail_error'] = $mailer->lastError; // Store error for UI debugging
        }

        return $result;
    }
}

// OOP Wrapper Class
class Mailer {
    public $lastError = '';

    public function send($toEmail, $toName, $subject, $bodyContent) {
        $wrappedBody = $this->wrapInTemplate($subject, $bodyContent);
        $res = send_email($toEmail, $subject, $wrappedBody);
        if (!$res && isset($_SESSION['mail_error'])) {
            $this->lastError = $_SESSION['mail_error'];
        }
        return $res;
    }

    private function wrapInTemplate($subject, $content) {
        return '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body { font-family: "Mulish", Arial, sans-serif; background-color: #f5f5f4; margin: 0; padding: 20px; color: #1e293b; }
                .email-container { max-width: 600px; margin: 0 auto; background: #ffffff; border: 1px solid #cbd5e1; border-radius: 12px; overflow: hidden; }
                .email-header { background-color: #0f172a; padding: 20px; text-align: center; border-bottom: 3px solid #4338ca; }
                .email-header h1 { color: #ffffff; margin: 0; font-size: 16px; font-weight: 800; text-transform: uppercase; letter-spacing: 1px; }
                .email-header p { color: #818cf8; margin: 4px 0 0; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 1.5px; }
                .email-body { padding: 30px 24px; font-size: 14px; line-height: 1.6; color: #334155; }
                .email-footer { background-color: #f8fafc; padding: 16px; text-align: center; border-top: 1px solid #e2e8f0; font-size: 10px; color: #64748b; font-family: monospace; }
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">
                    <h1>Best Western Recruitment</h1>
                    <p>Core HR Engine System Platform</p>
                </div>
                <div class="email-body">
                    ' . $content . '
                </div>
                <div class="email-footer">
                    &copy; ' . date('Y') . ' HR Engine System • Dynamic Secure Architecture Protocol
                </div>
            </div>
        </body>
        </html>';
    }
}