<?php
// Simple SMTP Mailer — works with Gmail, Outlook etc.

function sendMail($to, $subject, $htmlBody, $textBody = '') {
    $host     = getSetting('mail_host')       ?: '';
    $port     = intval(getSetting('mail_port') ?: 587);
    $user     = getSetting('mail_username')   ?: '';
    $pass     = getSetting('mail_password')   ?: '';
    $fromName = getSetting('mail_from_name')  ?: SITE_NAME;
    $fromMail = getSetting('mail_from_email') ?: $user;
    $enc      = getSetting('mail_encryption') ?: 'tls';

    if (!$host || !$user || !$pass) {
        return ['ok'=>false,'message'=>'SMTP credentials not configured in Settings → Email Server'];
    }

    try {
        // Connect
        $ctx = stream_context_create([
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true,
            ]
        ]);

        $prefix = ($enc === 'ssl') ? 'ssl://' : '';
        $sock   = stream_socket_client($prefix.$host.':'.$port, $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $ctx);

        if (!$sock) {
            return ['ok'=>false,'message'=>"Cannot connect to $host:$port — $errstr ($errno)"];
        }

        stream_set_timeout($sock, 20);

        // Helper
        $recv = function() use ($sock) {
            $buf = '';
            while(!feof($sock)) {
                $line = fgets($sock, 1024);
                $buf .= $line;
                if (strlen($line) >= 4 && $line[3] === ' ') break;
            }
            return $buf;
        };
        $send = function($cmd) use ($sock) {
            fputs($sock, $cmd."\r\n");
        };

        $r = $recv(); // 220 greeting
        if (substr($r,0,3) !== '220') {
            fclose($sock);
            return ['ok'=>false,'message'=>'SMTP greeting failed: '.trim($r)];
        }

        // EHLO
        $send("EHLO ".gethostname());
        $r = $recv();

        // STARTTLS
        if ($enc === 'tls') {
            $send("STARTTLS");
            $r = $recv();
            if (substr($r,0,3) !== '220') {
                fclose($sock);
                return ['ok'=>false,'message'=>'STARTTLS failed: '.trim($r)];
            }
            stream_socket_enable_crypto($sock, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
            $send("EHLO ".gethostname());
            $r = $recv();
        }

        // AUTH LOGIN
        $send("AUTH LOGIN");
        $r = $recv(); // 334
        $send(base64_encode($user));
        $r = $recv(); // 334
        $send(base64_encode($pass));
        $r = $recv(); // 235
        if (substr($r,0,3) !== '235') {
            fclose($sock);
            return ['ok'=>false,'message'=>'Auth failed: '.trim($r).' (Check username/password or App Password)'];
        }

        // MAIL FROM
        $send("MAIL FROM: <$fromMail>");
        $r = $recv();
        if (substr($r,0,3) !== '250') {
            fclose($sock);
            return ['ok'=>false,'message'=>'MAIL FROM rejected: '.trim($r)];
        }

        // RCPT TO
        $send("RCPT TO: <$to>");
        $r = $recv();
        if (substr($r,0,3) !== '250') {
            fclose($sock);
            return ['ok'=>false,'message'=>'RCPT TO rejected: '.trim($r)];
        }

        // DATA
        $send("DATA");
        $r = $recv(); // 354

        $boundary = 'boundary_'.md5(uniqid());
        $headers  = "From: =?UTF-8?B?".base64_encode($fromName)."?= <$fromMail>\r\n";
        $headers .= "To: $to\r\n";
        $headers .= "Subject: =?UTF-8?B?".base64_encode($subject)."?=\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n";
        $headers .= "Date: ".date('r')."\r\n";
        $headers .= "Message-ID: <".time().".".rand()."@".gethostname().">\r\n";

        $body  = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=UTF-8\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($textBody ?: strip_tags($htmlBody)))."\r\n";
        $body .= "--$boundary\r\n";
        $body .= "Content-Type: text/html; charset=UTF-8\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($htmlBody))."\r\n";
        $body .= "--$boundary--\r\n";

        fputs($sock, $headers."\r\n".$body."\r\n.\r\n");
        $r = $recv();
        if (substr($r,0,3) !== '250') {
            fclose($sock);
            return ['ok'=>false,'message'=>'Message rejected: '.trim($r)];
        }

        $send("QUIT");
        fclose($sock);
        return ['ok'=>true,'message'=>'Email sent successfully!'];

    } catch(Exception $e) {
        return ['ok'=>false,'message'=>$e->getMessage()];
    }
}

function sendOTPEmail($to, $otp, $name = '') {
    $siteName = SITE_NAME;
    $subject  = "[$siteName] Device Reset OTP — $otp";
    $html = "<!DOCTYPE html><html><body style='margin:0;padding:0;background:#f5f7fa;font-family:Arial,sans-serif'>
    <div style='max-width:480px;margin:0 auto;padding:20px'>
        <div style='background:linear-gradient(135deg,#0d1f4e,#1a3c8f);padding:24px;border-radius:16px 16px 0 0;text-align:center'>
            <div style='font-size:22px;font-weight:800;color:white'>$siteName</div>
            <div style='font-size:12px;color:rgba(255,255,255,0.7);margin-top:4px'>Device Reset OTP</div>
        </div>
        <div style='background:white;padding:28px;border-radius:0 0 16px 16px'>
            ".($name ? "<p style='color:#333;font-size:15px'>Hello <b>".htmlspecialchars($name)."</b>,</p>" : '')."
            <p style='color:#555;font-size:14px;margin-bottom:20px'>Use the OTP below to reset your device:</p>
            <div style='background:#f0f4ff;border-radius:12px;padding:24px;text-align:center;margin:20px 0'>
                <div style='font-size:40px;font-weight:900;color:#1a3c8f;letter-spacing:10px;font-family:monospace'>$otp</div>
                <div style='font-size:12px;color:#aaa;margin-top:10px'>⏱️ Valid for 10 minutes</div>
            </div>
            <p style='font-size:12px;color:#aaa'>If you did not request this, please ignore this email.</p>
        </div>
    </div>
    </body></html>";
    $text = "[$siteName] Your Device Reset OTP is: $otp (Valid for 10 minutes)";
    return sendMail($to, $subject, $html, $text);
}
