<?php
/**
 * DWSK Mailer
 * ---------------------------------------------------------------
 * Sends email via PHPMailer/SMTP when configured (recommended for
 * production, since most hosts' native mail() is unreliable / easily
 * marked as spam). Falls back to PHP's built-in mail() function
 * (including manual MIME construction for attachments) so the site
 * keeps working even before SMTP is set up.
 *
 * To enable PHPMailer:
 *   1. composer require phpmailer/phpmailer
 *      (Truehost cPanel: use "Setup Node.js/PHP App" > Terminal, or
 *      SSH access, or the Softaculous/Composer tool in cPanel.)
 *   2. Fill in SMTP_* constants in includes/config.php
 *   3. Set SMTP_ENABLED to true in includes/config.php
 */

if (!defined('DWSK_APP')) {
    http_response_code(403);
    exit('Direct access not permitted.');
}

/**
 * Send an email with optional file attachments.
 *
 * @param string $to
 * @param string $subject
 * @param string $htmlBody
 * @param array  $attachments Array of ['path' => string, 'name' => string]
 * @param string|null $replyTo
 * @return bool
 */
function send_branded_email(string $to, string $subject, string $htmlBody, array $attachments = [], ?string $replyTo = null): bool
{
    $vendorAutoload = __DIR__ . '/../vendor/autoload.php';

    if (SMTP_ENABLED && file_exists($vendorAutoload)) {
        require_once $vendorAutoload;
        return send_via_phpmailer($to, $subject, $htmlBody, $attachments, $replyTo);
    }

    // Fallback: native mail() with manual MIME for attachments
    return send_via_native_mail($to, $subject, $htmlBody, $attachments, $replyTo);
}

/**
 * Send using PHPMailer + SMTP (requires composer install).
 */
function send_via_phpmailer(string $to, string $subject, string $htmlBody, array $attachments, ?string $replyTo): bool
{
    try {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD;
        $mail->SMTPSecure = SMTP_SECURE === 'ssl'
            ? PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS
            : PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = SMTP_PORT;

        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($to);
        if ($replyTo) {
            $mail->addReplyTo($replyTo);
        }

        foreach ($attachments as $att) {
            if (!empty($att['path']) && file_exists($att['path'])) {
                $mail->addAttachment($att['path'], $att['name'] ?? basename($att['path']));
            }
        }

        $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 (\Throwable $e) {
        log_error('phpmailer_send', $e);
        return false;
    }
}

/**
 * Fallback: send via native mail() with hand-built multipart MIME,
 * so attachments still work even without PHPMailer/Composer installed.
 */
function send_via_native_mail(string $to, string $subject, string $htmlBody, array $attachments, ?string $replyTo): bool
{
    $boundary = md5((string) microtime());

    $headers  = "From: " . SMTP_FROM_NAME . " <" . SMTP_FROM_EMAIL . ">\r\n";
    if ($replyTo) {
        $headers .= "Reply-To: {$replyTo}\r\n";
    }
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";

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

    foreach ($attachments as $att) {
        if (empty($att['path']) || !file_exists($att['path'])) {
            continue;
        }
        $fileContent = chunk_split(base64_encode((string) file_get_contents($att['path'])));
        $fileName = $att['name'] ?? basename($att['path']);
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Type: application/octet-stream; name=\"{$fileName}\"\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n";
        $body .= "Content-Disposition: attachment; filename=\"{$fileName}\"\r\n\r\n";
        $body .= $fileContent . "\r\n\r\n";
    }

    $body .= "--{$boundary}--";

    return @mail($to, $subject, $body, $headers);
}

/**
 * Wrap inner HTML content in the shared DWSK branded email template
 * (logo, brand colours, footer with contact details).
 */
function dwsk_email_template(string $heading, string $innerHtml): string
{
    $logo = e(SITE_LOGO_URL);
    $navy = BRAND_NAVY;
    $emerald = BRAND_EMERALD;
    $site = e(SITE_NAME);
    $year = date('Y');

    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin:0;padding:0;background:#F1F5F9;font-family:Arial,Helvetica,sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#F1F5F9;padding:30px 0;">
    <tr><td align="center">
      <table role="presentation" width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;max-width:600px;width:100%;">
        <tr>
          <td style="background:{$navy};padding:28px 32px;text-align:center;">
            <img src="{$logo}" alt="{$site}" width="64" height="64" style="border-radius:50%;display:inline-block;margin-bottom:10px;">
            <div style="color:#ffffff;font-size:18px;font-weight:bold;font-family:Arial,sans-serif;">{$site}</div>
            <div style="color:{$emerald};font-size:12px;letter-spacing:0.05em;text-transform:uppercase;margin-top:2px;">Crafting Your Future</div>
          </td>
        </tr>
        <tr>
          <td style="padding:32px;">
            <h2 style="color:{$navy};font-size:20px;margin:0 0 16px;">{$heading}</h2>
            <div style="color:#334155;font-size:15px;line-height:1.6;">
              {$innerHtml}
            </div>
          </td>
        </tr>
        <tr>
          <td style="background:#071527;padding:22px 32px;color:rgba(255,255,255,0.7);font-size:12.5px;line-height:1.7;">
            <div style="color:#ffffff;font-weight:bold;margin-bottom:6px;">{$site}</div>
            <div>Nairobi, Kenya &middot; info@dynamicwritingservices.com</div>
            <div>+254 707 803 167 / +254 757 432 808 &middot; WhatsApp: +254 774 730 172</div>
            <div style="margin-top:10px;color:rgba(255,255,255,0.45);">&copy; {$year} {$site}. All Rights Reserved.</div>
          </td>
        </tr>
      </table>
    </td></tr>
  </table>
</body>
</html>
HTML;
}
