<?php
declare(strict_types=1);

use PHPMailer\PHPMailer\Exception as MailException;
use PHPMailer\PHPMailer\PHPMailer;

function rsvp_load_phpmailer(): bool
{
    $autoload = __DIR__ . '/../vendor/autoload.php';
    if (is_file($autoload)) {
        require_once $autoload;
        return class_exists(PHPMailer::class);
    }

    $base = __DIR__ . '/../vendor/phpmailer/phpmailer/src';
    foreach (['Exception.php', 'PHPMailer.php', 'SMTP.php'] as $file) {
        $path = $base . '/' . $file;
        if (!is_file($path)) {
            return false;
        }
        require_once $path;
    }

    return class_exists(PHPMailer::class);
}

function rsvp_plain_text_email(array $data): string
{
    $status = $data['attendance'] === 'yes' ? 'attending' : 'unable to attend';

    return implode("\n", [
        'Dear ' . $data['full_name'] . ',',
        '',
        "Thank you for your RSVP for E-Babe's Season Of Thanksgiving.",
        'We have recorded that you are ' . $status . '.',
        'Category: ' . ($data['category'] ?? ''),
        $data['attendance'] === 'yes' ? 'Party size: ' . $data['party_size'] : '',
        '',
        'Event: Celebrating Mrs. Catherine Chidinma Anyadimaju - A Season Of Thanksgiving',
        'Date: 8 November 2026',
        'Location: Lagos, Nigeria',
        '',
        'With gratitude,',
        'Book NetX',
    ]);
}

function rsvp_crest_cid(): string
{
    return 'ebabe-crest';
}

function rsvp_html_email(array $data): string
{
    $firstName = htmlspecialchars(strtok($data['full_name'], ' ') ?: $data['full_name'], ENT_QUOTES, 'UTF-8');
    $fullName = htmlspecialchars($data['full_name'], ENT_QUOTES, 'UTF-8');
    $crestSrc = 'cid:' . rsvp_crest_cid();
    $statusLine = $data['attendance'] === 'yes'
        ? 'We are delighted to record that you will be joining us.'
        : 'Thank you for letting us know. Your response has been safely recorded.';
    $category = htmlspecialchars((string) ($data['category'] ?? ''), ENT_QUOTES, 'UTF-8');
    $partyLine = $data['attendance'] === 'yes'
        ? '<tr><td style="padding:10px 0;color:#6B5D74;">Party size</td><td align="right" style="padding:10px 0;color:#2B1B33;font-weight:600;">' . (int) $data['party_size'] . '</td></tr>'
        : '';

    return '<!doctype html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#FFFFFF;font-family:Georgia,Times New Roman,serif;color:#2B1B33;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#FFFFFF;padding:28px 14px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:620px;background:#FFFFFF;border:1px solid #E9DFF0;">
          <tr>
            <td style="padding:42px 34px 30px;text-align:center;background:linear-gradient(180deg,#FDFBFE,#FFFFFF);">
              <div style="font-size:12px;letter-spacing:5px;text-transform:uppercase;color:#673D84;">RSVP Received</div>
              <img src="' . $crestSrc . '" width="132" height="132" alt="E-Babe monogram" style="display:block;width:132px;height:132px;border-radius:50%;margin:20px auto 14px;">
              <p style="margin:0;color:#6B5D74;font-size:17px;font-style:italic;">Celebrating Mrs. Catherine Chidinma Anyadimaju - A Season Of Thanksgiving</p>
            </td>
          </tr>
          <tr>
            <td style="padding:0 34px 34px;">
              <div style="height:1px;background:linear-gradient(90deg,transparent,#8741D8,transparent);margin-bottom:30px;"></div>
              <p style="font-size:20px;line-height:1.6;margin:0 0 14px;">Dear ' . $firstName . ',</p>
              <p style="font-size:18px;line-height:1.7;margin:0 0 24px;color:#6B5D74;">' . htmlspecialchars($statusLine, ENT_QUOTES, 'UTF-8') . '</p>
              <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-top:1px solid #E9DFF0;border-bottom:1px solid #E9DFF0;margin:24px 0;">
                <tr><td style="padding:16px 0 10px;color:#6B5D74;">Guest</td><td align="right" style="padding:16px 0 10px;color:#2B1B33;font-weight:600;">' . $fullName . '</td></tr>
                <tr><td style="padding:10px 0;color:#6B5D74;">Category</td><td align="right" style="padding:10px 0;color:#2B1B33;font-weight:600;">' . $category . '</td></tr>
                <tr><td style="padding:10px 0;color:#6B5D74;">Response</td><td align="right" style="padding:10px 0;color:#2B1B33;font-weight:600;">' . ($data['attendance'] === 'yes' ? 'Joyfully accepts' : 'Regretfully declines') . '</td></tr>
                ' . $partyLine . '
                <tr><td style="padding:10px 0;color:#6B5D74;">Date</td><td align="right" style="padding:10px 0;color:#2B1B33;font-weight:600;">8 November 2026</td></tr>
                <tr><td style="padding:10px 0 16px;color:#6B5D74;">Location</td><td align="right" style="padding:10px 0 16px;color:#2B1B33;font-weight:600;">Lagos, Nigeria</td></tr>
              </table>
              <p style="font-size:16px;line-height:1.7;color:#6B5D74;margin:0;">More details to follow.</p>
              <p style="font-size:16px;line-height:1.7;color:#6B5D74;margin:22px 0 0;">With gratitude,<br><strong style="color:#673D84;">Book NetX</strong></p>
            </td>
          </tr>
          <tr>
            <td style="padding:20px 34px;text-align:center;background:#F8F3FB;color:#6B5D74;font-size:12px;letter-spacing:3px;text-transform:uppercase;">&copy; 2026 Book NetX</td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>';
}

function rsvp_notification_plain_text(array $data): string
{
    return implode("\n", [
        'New RSVP received',
        '',
        'Name: ' . $data['full_name'],
        'Email: ' . $data['email'],
        'Phone: ' . ($data['phone'] ?: 'Not provided'),
        'Category: ' . ($data['category'] ?? ''),
        'Response: ' . ($data['attendance'] === 'yes' ? 'Joyfully accepts' : 'Regretfully declines'),
        'Party size: ' . (int) $data['party_size'],
        'Note: ' . ($data['note'] ?: 'None'),
        '',
        'Submitted: ' . ($data['created_at'] ?? 'Just now'),
    ]);
}

function rsvp_notification_html(array $data): string
{
    $name = htmlspecialchars($data['full_name'], ENT_QUOTES, 'UTF-8');
    $email = htmlspecialchars($data['email'], ENT_QUOTES, 'UTF-8');
    $phone = htmlspecialchars($data['phone'] ?: 'Not provided', ENT_QUOTES, 'UTF-8');
    $category = htmlspecialchars((string) ($data['category'] ?? ''), ENT_QUOTES, 'UTF-8');
    $response = $data['attendance'] === 'yes' ? 'Joyfully accepts' : 'Regretfully declines';
    $note = nl2br(htmlspecialchars($data['note'] ?: 'None', ENT_QUOTES, 'UTF-8'));

    return '<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body style="margin:0;background:#FFFFFF;font-family:Georgia,Times New Roman,serif;color:#2B1B33;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="padding:24px;background:#FFFFFF;">
    <tr><td align="center">
      <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:620px;background:#FFFFFF;border:1px solid #E9DFF0;">
        <tr><td style="padding:30px 32px;text-align:center;background:#F8F3FB;">
          <div style="font-size:12px;letter-spacing:4px;text-transform:uppercase;color:#673D84;">New RSVP</div>
          <h1 style="margin:10px 0 0;font-size:28px;font-weight:400;color:#2B1B33;">E-Babe\'s Season Of Thanksgiving</h1>
        </td></tr>
        <tr><td style="padding:28px 32px;">
          <table role="presentation" width="100%" cellspacing="0" cellpadding="0">
            <tr><td style="padding:10px 0;color:#6B5D74;">Name</td><td align="right" style="padding:10px 0;font-weight:600;">' . $name . '</td></tr>
            <tr><td style="padding:10px 0;color:#6B5D74;">Email</td><td align="right" style="padding:10px 0;font-weight:600;">' . $email . '</td></tr>
            <tr><td style="padding:10px 0;color:#6B5D74;">Phone</td><td align="right" style="padding:10px 0;font-weight:600;">' . $phone . '</td></tr>
            <tr><td style="padding:10px 0;color:#6B5D74;">Category</td><td align="right" style="padding:10px 0;font-weight:600;">' . $category . '</td></tr>
            <tr><td style="padding:10px 0;color:#6B5D74;">Response</td><td align="right" style="padding:10px 0;font-weight:600;">' . $response . '</td></tr>
            <tr><td style="padding:10px 0;color:#6B5D74;">Party size</td><td align="right" style="padding:10px 0;font-weight:600;">' . (int) $data['party_size'] . '</td></tr>
          </table>
          <div style="margin-top:20px;padding:18px;border-top:1px solid #E9DFF0;border-bottom:1px solid #E9DFF0;color:#6B5D74;line-height:1.6;">' . $note . '</div>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body>
</html>';
}

function rsvp_apply_smtp(PHPMailer $mail, array $mailConfig): void
{
    $mail->isSMTP();
    $mail->Host = $mailConfig['host'];
    $mail->SMTPAuth = true;
    $mail->Username = $mailConfig['username'];
    $mail->Password = $mailConfig['password'];
    $mail->Port = (int) $mailConfig['port'];
    if (!empty($mailConfig['encryption'])) {
        $mail->SMTPSecure = $mailConfig['encryption'];
    }
    $mail->CharSet = 'UTF-8';
}

function rsvp_send_confirmation_email(array $data): array
{
    if (!rsvp_load_phpmailer()) {
        return ['sent' => false, 'error' => 'PHPMailer is not installed. Run composer install.'];
    }

    $config = rsvp_config();
    $mailConfig = $config['mail'];

    try {
        $mail = new PHPMailer(true);
        rsvp_apply_smtp($mail, $mailConfig);
        $mail->setFrom($mailConfig['from_email'], $mailConfig['from_name']);
        $mail->addReplyTo($mailConfig['reply_to'] ?: $config['event']['reply_to'], $mailConfig['from_name']);
        $mail->addAddress($data['email'], $data['full_name']);
        $crestPath = __DIR__ . '/../crest.png';
        if (is_file($crestPath)) {
            $mail->addEmbeddedImage($crestPath, rsvp_crest_cid(), 'crest.png');
        }
        $mail->Subject = "Your RSVP has been received - E-Babe's Season Of Thanksgiving";
        $mail->isHTML(true);
        $mail->Body = rsvp_html_email($data);
        $mail->AltBody = rsvp_plain_text_email($data);
        $mail->send();

        return ['sent' => true, 'error' => null];
    } catch (MailException $exception) {
        return ['sent' => false, 'error' => $exception->getMessage()];
    }
}

function rsvp_send_admin_notification(array $data): array
{
    if (!rsvp_load_phpmailer()) {
        return ['sent' => false, 'error' => 'PHPMailer is not installed. Run composer install.'];
    }

    $config = rsvp_config();
    $mailConfig = $config['mail'];
    $recipients = $mailConfig['notification_recipients'] ?? [];

    if (!$recipients) {
        return ['sent' => true, 'error' => null];
    }

    try {
        $mail = new PHPMailer(true);
        rsvp_apply_smtp($mail, $mailConfig);
        $mail->setFrom($mailConfig['from_email'], $mailConfig['from_name']);
        $mail->addReplyTo($data['email'], $data['full_name']);
        foreach ($recipients as $recipient) {
            $mail->addAddress($recipient);
        }
        $mail->Subject = 'New RSVP: ' . $data['full_name'] . " - E-Babe's Season Of Thanksgiving";
        $mail->isHTML(true);
        $mail->Body = rsvp_notification_html($data);
        $mail->AltBody = rsvp_notification_plain_text($data);
        $mail->send();

        return ['sent' => true, 'error' => null];
    } catch (MailException $exception) {
        return ['sent' => false, 'error' => $exception->getMessage()];
    }
}
