<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

require_once 'vendor/autoload.php';

header('Content-Type: application/json');

function jsonOut(bool $success, string $msg): void
{
    echo json_encode(['success' => $success, 'msg' => $msg]);
    exit;
}

$to = $_POST['to'] ?? '';
$subject = $_POST['subject'] ?? '';
$message = $_POST['message'] ?? '';
$from_account = $_POST['from_account'] ?? '';

if (!$to || !$subject || !$message || !$from_account) {
    jsonOut(false, 'Missing required fields.');
}

// === Load .env ===
function parseEnv(): array
{
    $path = __DIR__ . '/.env';
    if (!file_exists($path))
        return [];

    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $data = [];
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#' || strpos($line, '=') === false)
            continue;
        [$k, $v] = explode('=', $line, 2);
        $v = trim(explode('#', $v)[0]); // strip inline comments
        $v = trim($v, '"\'');           // strip quotes
        $data[trim($k)] = $v;
    }
    return $data;
}

function getEnvEmails(): array
{
    $data = parseEnv();
    $accounts = [];
    foreach ($data as $key => $val) {
        if (substr($key, -6) === '_EMAIL') {
            $prefix = substr($key, 0, -6);
            $pass = $data["{$prefix}_PASS"] ?? null;
            if ($val && $pass) {
                $accounts[$val] = $pass;
            }
        }
    }
    return $accounts;
}

$env = parseEnv();
$accounts = getEnvEmails();
$password = $accounts[$from_account] ?? null;

// Pull school name from .env (SCHOOL_NAME_1 preferred, fallback to SCHOOL_NAME)
$schoolName = $env['SCHOOL_NAME_1'] ?? $env['SCHOOL_NAME'] ?? 'Adesina College, Ibadan';
$baseUrl = $env['BASE_URL'] ?? 'https://acionlineportal.com.ng';
$idAddress = $env['id_address'] ?? '2, Kolawole Ajadi Crescent, Alagbayun, Akobo, Ibadan.';
if (!$password) {
    jsonOut(false, 'Sender account not found.');
}

// === Build a clean, non-spammy HTML email body ===
function buildEmailBody(string $senderEmail, string $rawMessage, string $schoolName, string $baseUrl, string $idAddress): string
{
    $safeMessage = strip_tags($rawMessage, '<p><br><b><strong><i><em><u><ul><ol><li><h1><h2><h3><h4><span><a><img>');
    $domain = preg_replace('#^https?://#', '', rtrim($baseUrl, '/'));

    return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Message from {$schoolName}</title>
</head>
<body style="margin:0;padding:0;background-color:#f4f4f4;font-family:Arial,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f4f4;padding:30px 0;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:6px;overflow:hidden;border:1px solid #e0e0e0;">
          <!-- Header -->
          <tr>
            <td style="background-color:#1a3c6e;padding:20px 30px;">
              <p style="margin:0;color:#ffffff;font-size:18px;font-weight:bold;">{$schoolName}</p>
              <p style="margin:4px 0 0;color:#c8d8f0;font-size:13px;">Official Communication</p>
            </td>
          </tr>
          <!-- Body -->
          <tr>
            <td style="padding:30px;">
              <p style="margin:0 0 16px;font-size:15px;color:#333333;line-height:1.6;">{$safeMessage}</p>
            </td>
          </tr>
          <!-- Footer -->
          <tr>
            <td style="background-color:#f9f9f9;padding:16px 30px;border-top:1px solid #e0e0e0;">
              <p style="margin:0;font-size:12px;color:#888888;">
                This message was sent from <strong>{$senderEmail}</strong> on behalf of {$schoolName}.<br>
                {$idAddress} &mdash;
                <a href="{$baseUrl}" style="color:#1a3c6e;text-decoration:none;">{$domain}</a>
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
HTML;
}

// === Send email ===
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'mail.acionlineportal.com.ng';
    $mail->SMTPAuth = true;
    $mail->Username = $from_account;
    $mail->Password = $password;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port = 465;
    $mail->Timeout = 10;

    $mail->setFrom($from_account, $schoolName);
    $mail->addAddress($to);
    $mail->addReplyTo($from_account, $schoolName);
    $mail->isHTML(true);
    $mail->CharSet = 'UTF-8';
    $mail->Subject = $subject;
    $mail->Body = buildEmailBody($from_account, $message, $schoolName, $baseUrl, $idAddress);
    $mail->AltBody = strip_tags($message); // plain-text fallback

    $mail->send();

    // Save to Sent folder via IMAP (best-effort, don't fail if it errors)
    try {
        $imapStream = @imap_open(
            '{mail.acionlineportal.com.ng:993/imap/ssl/novalidate-cert}INBOX',
            $from_account,
            $password
        );
        if ($imapStream) {
            imap_append(
                $imapStream,
                '{mail.acionlineportal.com.ng:993/imap/ssl/novalidate-cert}INBOX.Sent',
                $mail->getSentMIMEMessage()
            );
            imap_close($imapStream);
        }
    } catch (\Throwable $ignored) {
    }

    jsonOut(true, 'Reply sent successfully.');
} catch (Exception $e) {
    jsonOut(false, 'Reply failed: ' . $mail->ErrorInfo);
}
