<?php
/**
 * Mail helper — calls external SMTP service URL.
 *
 * Mirrors the Android backend's `sendEmailOTPViaUrl()` pattern.
 * The actual mail sender is a separate PHP service that receives
 * GET params (email, token) and sends the SMTP message.
 */

declare(strict_types=1);

class Mail
{
    /**
     * Send an OTP email by hitting the configured SMTP URL.
     *
     * @param string $email     Recipient
     * @param string $otp       6-digit OTP (or token for reset link)
     * @param string $purpose   'signup' | 'forget' | 'login'
     * @return bool             true if request succeeded
     */
    public static function sendOtp(string $email, string $otp, string $purpose = 'signup'): bool
    {
        $urlMap = [
            'signup' => (string)env('SMTP_SIGNUP_URL', ''),
            'login'  => (string)env('SMTP_SIGNUP_URL', ''),
            'forget' => (string)env('SMTP_FORGET_URL', ''),
        ];
        $base = $urlMap[$purpose] ?? '';
        if ($base === '') {
            Logger::error('SMTP URL not configured for purpose', ['purpose' => $purpose]);
            return false;
        }

        $url = $base . (str_contains($base, '?') ? '&' : '?')
             . 'email=' . urlencode($email)
             . '&token=' . urlencode($otp);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 8,
            CURLOPT_CONNECTTIMEOUT => 4,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT      => 'DroidTester-Publisher/1.0',
        ]);
        $body = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err  = curl_error($ch);
        curl_close($ch);

        if ($body === false || $code >= 400) {
            Logger::error('SMTP URL call failed', [
                'purpose' => $purpose,
                'http'    => $code,
                'err'     => $err,
                'body'    => substr((string)$body, 0, 200),
            ]);
            return false;
        }

        Logger::info('SMTP URL call ok', ['purpose' => $purpose, 'email' => $email]);
        return true;
    }

    /**
     * Send password reset link via the FORGET URL.
     */
    public static function sendResetLink(string $email, string $token): bool
    {
        return self::sendOtp($email, $token, 'forget');
    }
}
