<?php
declare(strict_types=1);

require_once __DIR__ . '/../libs/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/../libs/phpmailer/src/SMTP.php';
require_once __DIR__ . '/../libs/phpmailer/src/Exception.php';
require_once __DIR__ . '/ErrorLogger.php';

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

function sendListSignupNotification(PDO $db, array $form, array $recipientData, array $context = []): bool
{
    if (empty($form['notify_on_signup']) || empty($form['from_identity_id'])) {
        return false;
    }

    try {
        $senderStmt = $db->prepare(
            'SELECT id, name, email, dkim_selector, dkim_private_key
               FROM sender_identities
              WHERE id = :id
                AND is_active = 1
              LIMIT 1'
        );
        $senderStmt->execute([':id' => (int) $form['from_identity_id']]);
        $sender = $senderStmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if (!$sender || empty($sender['email'])) {
            ErrorLogger::logSqlError('list_signup_notification: sender missing or inactive');
            return false;
        }

        $smtpStmt = $db->query(
            'SELECT *
               FROM smtp_accounts
              WHERE is_active = 1
           ORDER BY last_used_at ASC, id ASC
              LIMIT 1'
        );
        $smtp = $smtpStmt ? ($smtpStmt->fetch(PDO::FETCH_ASSOC) ?: null) : null;

        if (!$smtp) {
            ErrorLogger::logSqlError('list_signup_notification: no active smtp account found');
            return false;
        }

        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = $smtp['smtp_host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $smtp['smtp_user'];
        $mail->Password   = $smtp['smtp_pass'];
        $mail->Port       = (int) $smtp['smtp_port'];
        $mail->SMTPSecure = $smtp['smtp_secure'] ?: 'tls';
        $mail->CharSet    = 'UTF-8';
        $mail->Encoding   = 'base64';
        $mail->setFrom((string) $sender['email'], (string) ($sender['name'] ?? ''));
        $mail->addAddress((string) $sender['email'], (string) ($sender['name'] ?? ''));
        $mail->Sender = (string) ($smtp['smtp_email'] ?? $smtp['smtp_user']);
        $mail->isHTML(true);

        if (!empty($recipientData['email'])) {
            $mail->addReplyTo((string) $recipientData['email']);
        }

        if (!empty($sender['dkim_selector']) && !empty($sender['dkim_private_key'])) {
            $mail->DKIM_domain         = substr((string) strrchr((string) $sender['email'], '@'), 1);
            $mail->DKIM_selector       = (string) $sender['dkim_selector'];
            $mail->DKIM_private_string = (string) $sender['dkim_private_key'];
            $mail->DKIM_identity       = (string) $sender['email'];
        }

        $subject = '[MR9] Neue Formular-Anmeldung: ' . (string) ($form['list_name'] ?? $form['name'] ?? 'Liste');
        $submittedFields = $context['submitted_fields'] ?? [];
        $customFields = $context['custom_fields'] ?? [];
        $submittedAt = $context['submitted_at'] ?? date('Y-m-d H:i:s');
        $anonymizedIp = $context['anonymized_ip'] ?? '';
        $referrer = $context['referrer'] ?? '';
        $requiresDoi = !empty($form['requires_doi']) ? 'Ja' : 'Nein';

        $rows = [];
        $rows[] = ['Liste', (string) ($form['list_name'] ?? '')];
        $rows[] = ['Formular', (string) ($form['name'] ?? '')];
        $rows[] = ['Zeitpunkt', (string) $submittedAt];
        $rows[] = ['E-Mail', (string) ($recipientData['email'] ?? '')];
        $rows[] = ['Anrede', (string) ($recipientData['anrede'] ?? '')];
        $rows[] = ['Vorname', (string) ($recipientData['vorname'] ?? '')];
        $rows[] = ['Nachname', (string) ($recipientData['nachname'] ?? '')];
        $rows[] = ['DOI aktiv', $requiresDoi];

        if ($anonymizedIp !== '') {
            $rows[] = ['IP', (string) $anonymizedIp];
        }
        if ($referrer !== '') {
            $rows[] = ['Referrer', (string) $referrer];
        }

        foreach ($submittedFields as $label => $value) {
            if ($value === '' || $value === null) {
                continue;
            }
            $rows[] = [(string) $label, is_array($value) ? implode(', ', $value) : (string) $value];
        }

        foreach ($customFields as $label => $value) {
            if ($value === '' || $value === null) {
                continue;
            }
            $rows[] = ['Feld: ' . (string) $label, is_array($value) ? implode(', ', $value) : (string) $value];
        }

        $htmlBody = '<h2>Neue Formular-Anmeldung</h2><table cellpadding="6" cellspacing="0" border="1">';
        $plainBody = "Neue Formular-Anmeldung\n\n";

        foreach ($rows as [$label, $value]) {
            $htmlBody .= '<tr><th align="left">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</th><td>' . nl2br(htmlspecialchars($value, ENT_QUOTES, 'UTF-8')) . '</td></tr>';
            $plainBody .= $label . ': ' . $value . "\n";
        }

        $htmlBody .= '</table>';

        $mail->Subject = $subject;
        $mail->Body = $htmlBody;
        $mail->AltBody = $plainBody;
        $mail->send();

        $touchStmt = $db->prepare('UPDATE smtp_accounts SET last_used_at = NOW() WHERE id = ?');
        $touchStmt->execute([(int) $smtp['id']]);

        ErrorLogger::logSqlSuccess('list_signup_notification: mail sent | context: ' . json_encode([
            'list_id' => (int) ($form['list_id'] ?? 0),
            'recipient_id' => (int) ($recipientData['recipient_id'] ?? 0),
            'to' => (string) $sender['email'],
            'smtp_id' => (int) ($smtp['id'] ?? 0),
        ], JSON_UNESCAPED_UNICODE));

        return true;
    } catch (Exception $e) {
        ErrorLogger::logSqlError('list_signup_notification: send failed | error: ' . $e->getMessage());
        return false;
    } catch (Throwable $e) {
        ErrorLogger::logSqlError('list_signup_notification: unexpected error | error: ' . $e->getMessage());
        return false;
    }
}