<?php
/**
 * Sistema Central de E-mail
 * Usa PHPMailer via SMTP configurado em config-email.php
 */

// Carrega configurações de e-mail
$emailConfigPath = __DIR__ . '/../config-email.php';
if (file_exists($emailConfigPath) && !defined('SMTP_HOST')) {
    require_once $emailConfigPath;
}

/**
 * Envia um e-mail HTML usando PHPMailer ou mail() nativo como fallback
 *
 * @param string $toEmail  Destinatário
 * @param string $toName   Nome do destinatário
 * @param string $subject  Assunto
 * @param string $htmlBody Corpo HTML
 * @return bool
 */
function enviarEmail(string $toEmail, string $toName, string $subject, string $htmlBody): bool
{
    // Tenta PHPMailer primeiro
    $phpmailerPath = __DIR__ . '/../../adm/lib/phpmailer/src/PHPMailer.php';
    $phpmailerPath2 = __DIR__ . '/../lib/phpmailer/src/PHPMailer.php';

    if (file_exists($phpmailerPath) || file_exists($phpmailerPath2)) {
        return _enviarComPHPMailer($toEmail, $toName, $subject, $htmlBody);
    }

    // Fallback: SMTP manual via socket
    return _enviarComSMTPNativo($toEmail, $toName, $subject, $htmlBody);
}

function _enviarComPHPMailer(string $toEmail, string $toName, string $subject, string $htmlBody): bool
{
    $paths = [
        __DIR__ . '/../../adm/lib/phpmailer/src/PHPMailer.php',
        __DIR__ . '/../lib/phpmailer/src/PHPMailer.php',
    ];

    foreach ($paths as $path) {
        if (file_exists($path)) {
            $dir = dirname($path);
            require_once $dir . '/PHPMailer.php';
            require_once $dir . '/SMTP.php';
            require_once $dir . '/Exception.php';
            break;
        }
    }

    try {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = defined('SMTP_HOST') ? SMTP_HOST : 'mail.catalogo44.com.br';
        $mail->SMTPAuth   = true;
        $mail->Username   = defined('SMTP_USER') ? SMTP_USER : '';
        $mail->Password   = defined('SMTP_PASS') ? SMTP_PASS : '';
        $mail->SMTPSecure = defined('SMTP_SECURE') ? SMTP_SECURE : 'ssl';
        $mail->Port       = defined('SMTP_PORT') ? SMTP_PORT : 465;
        $mail->CharSet    = 'UTF-8';
        $mail->setFrom(
            defined('SMTP_FROM_EMAIL') ? SMTP_FROM_EMAIL : SMTP_USER,
            defined('SMTP_FROM_NAME') ? SMTP_FROM_NAME : 'Loja'
        );
        $mail->addAddress($toEmail, $toName);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;
        $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $htmlBody));
        $mail->send();
        return true;
    } catch (\Exception $e) {
        error_log('[MAILER] PHPMailer falhou: ' . $e->getMessage());
        return false;
    }
}

function _enviarComSMTPNativo(string $toEmail, string $toName, string $subject, string $htmlBody): bool
{
    $host    = defined('SMTP_HOST')       ? SMTP_HOST       : 'mail.catalogo44.com.br';
    $user    = defined('SMTP_USER')       ? SMTP_USER       : '';
    $pass    = defined('SMTP_PASS')       ? SMTP_PASS       : '';
    $port    = defined('SMTP_PORT')       ? (int)SMTP_PORT  : 465;
    $secure  = defined('SMTP_SECURE')     ? SMTP_SECURE     : 'ssl';
    $from    = defined('SMTP_FROM_EMAIL') ? SMTP_FROM_EMAIL : $user;
    $fromName = defined('SMTP_FROM_NAME') ? SMTP_FROM_NAME  : 'Loja';

    $prefix = ($secure === 'ssl') ? 'ssl://' : 'tls://';
    $socket = @fsockopen($prefix . $host, $port, $errno, $errstr, 10);

    if (!$socket) {
        // Último fallback: mail() nativo
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: =?UTF-8?B?" . base64_encode($fromName) . "?= <{$from}>\r\n";
        $headers .= "To: =?UTF-8?B?" . base64_encode($toName) . "?= <{$toEmail}>\r\n";
        $subjectEncoded = "=?UTF-8?B?" . base64_encode($subject) . "?=";
        return mail($toEmail, $subjectEncoded, $htmlBody, $headers);
    }

    $read = function () use ($socket) {
        $data = '';
        while ($str = fgets($socket, 515)) {
            $data .= $str;
            if (substr($str, 3, 1) === ' ') break;
        }
        return $data;
    };

    $send = function (string $cmd) use ($socket, $read) {
        fputs($socket, $cmd . "\r\n");
        return $read();
    };

    try {
        $read(); // Banner
        $send("EHLO " . $host);
        $send("AUTH LOGIN");
        $send(base64_encode($user));
        $send(base64_encode($pass));
        $send("MAIL FROM:<{$from}>");
        $send("RCPT TO:<{$toEmail}>");
        $send("DATA");

        $boundary = md5(uniqid());
        $headers  = "From: =?UTF-8?B?" . base64_encode($fromName) . "?= <{$from}>\r\n";
        $headers .= "To: =?UTF-8?B?" . base64_encode($toName) . "?= <{$toEmail}>\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";

        $plainText = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $htmlBody));

        $body  = "--{$boundary}\r\n";
        $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
        $body .= $plainText . "\r\n";
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Type: text/html; charset=UTF-8\r\n\r\n";
        $body .= $htmlBody . "\r\n";
        $body .= "--{$boundary}--";

        fputs($socket, $headers . "\r\n" . $body . "\r\n.\r\n");
        $read();
        $send("QUIT");
        fclose($socket);
        return true;
    } catch (\Throwable $e) {
        error_log('[MAILER] SMTP nativo falhou: ' . $e->getMessage());
        fclose($socket);
        return false;
    }
}
