<?php

declare(strict_types=1);

require_once __DIR__ . '/resend_client.php';
require_once __DIR__ . '/registration_wizard.php';
require_once __DIR__ . '/contract_admin.php';
require_once __DIR__ . '/api_service.php';

function contract_brand_display_label(array $contract): string
{
    require_once __DIR__ . '/contract_form.php';

    $brands = contract_brands_from_record($contract);
    if ($brands === []) {
        return 'Karvi Partner';
    }

    $labels = array_map('contract_brand_label', $brands);

    return count($labels) > 1 ? implode(' und ', $labels) : $labels[0];
}

function contract_registration_recipient_email(array $contract): string
{
    foreach (['registration_email', 'email', 'partner_email'] as $key) {
        $value = trim((string)($contract[$key] ?? ''));
        if ($value !== '' && filter_var($value, FILTER_VALIDATE_EMAIL)) {
            return $value;
        }
    }

    return '';
}

function email_escape(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function email_layout(string $title, string $bodyHtml): string
{
    $safeTitle = email_escape($title);
    $config = email_config();
    $supportEmail = trim((string)($config['support_email'] ?? 'info@karvipartner.de'));
    $supportPhone = trim((string)($config['support_phone'] ?? '+49 1522 3649558'));

    return '<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>' . $safeTitle . '</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f6;font-family:Arial,Helvetica,sans-serif;color:#1a1a1f;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f4f4f6;padding:24px 12px;">
<tr><td align="center">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:640px;background:#ffffff;border-radius:16px;overflow:hidden;border:1px solid #e8e8ec;">
<tr><td style="background:#111114;padding:28px 32px;">
<div style="font-size:12px;letter-spacing:0.12em;text-transform:uppercase;color:#b8b8c2;margin-bottom:8px;">Karvi Partner</div>
<div style="font-size:24px;line-height:1.3;font-weight:700;color:#ffffff;">' . $safeTitle . '</div>
</td></tr>
<tr><td style="padding:32px;">' . $bodyHtml . '</td></tr>
<tr><td style="padding:0 32px 28px;">
<div style="border-top:1px solid #ececee;padding-top:18px;font-size:12px;line-height:1.6;color:#6b6b76;">
Karvi Partner mit Gulab und Flamers<br>
<a href="mailto:' . email_escape($supportEmail) . '" style="color:#111114;">' . email_escape($supportEmail) . '</a> · ' . email_escape($supportPhone) . '
</div>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>';
}

function email_info_table(array $rows): string
{
    if ($rows === []) {
        return '';
    }

    $html = '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:0 0 20px;">';

    foreach ($rows as $label => $value) {
        $value = trim((string)$value);
        if ($value === '') {
            continue;
        }

        $html .= '<tr>'
            . '<td style="padding:10px 12px;border-bottom:1px solid #f0f0f3;width:38%;font-size:13px;color:#6b6b76;vertical-align:top;">'
            . email_escape((string)$label)
            . '</td>'
            . '<td style="padding:10px 12px;border-bottom:1px solid #f0f0f3;font-size:14px;color:#111114;vertical-align:top;">'
            . nl2br(email_escape($value))
            . '</td>'
            . '</tr>';
    }

    $html .= '</table>';

    return $html;
}

function email_audit_block(array $record, int $index): string
{
    $title = 'Inhaber ' . ($index + 1);
    $rows = [
        'Name' => (string)($record['signer_name'] ?? ''),
        'Unterschrift am' => format_date((string)($record['signed_at'] ?? '')) . ' ' . substr((string)($record['signed_at'] ?? ''), 11),
        'Methode' => (string)($record['signature_method'] ?? ''),
        'IP-Adresse' => (string)($record['ip_address'] ?? ''),
        'Zeitzone' => (string)($record['timezone'] ?? ''),
        'Bildschirmauflösung' => (string)($record['screen_resolution'] ?? ''),
        'Standort' => (string)($record['full_address'] ?? ''),
        'Geo-Status' => (string)($record['geo_status'] ?? ''),
        'Koordinaten' => isset($record['latitude'], $record['longitude'])
            ? (string)$record['latitude'] . ', ' . (string)$record['longitude']
            : '',
        'Genauigkeit (m)' => isset($record['accuracy_meters']) ? (string)$record['accuracy_meters'] : '',
        'User-Agent' => (string)($record['user_agent'] ?? ''),
    ];

    $cid = 'signature-' . $index;
    $imageHtml = '<div style="margin-top:12px;padding:12px;background:#fafafb;border:1px solid #ececee;border-radius:12px;">'
        . '<div style="font-size:12px;color:#6b6b76;margin-bottom:8px;">Digitale Unterschrift</div>'
        . '<img src="cid:' . $cid . '" alt="Unterschrift" style="max-width:280px;height:auto;display:block;">'
        . '</div>';

    return '<div style="margin-bottom:24px;padding:18px;background:#fcfcfd;border:1px solid #ececee;border-radius:14px;">'
        . '<div style="font-size:15px;font-weight:700;color:#111114;margin-bottom:12px;">' . email_escape($title) . '</div>'
        . email_info_table($rows)
        . $imageHtml
        . '</div>';
}

function contract_build_customer_registration_email(array $contract, string $brandLabel, string $signedAt): array
{
    $restaurant = trim((string)($contract['restaurant_name'] ?? $contract['partner_name'] ?? ''));
    $config = email_config();
    $supportPhone = trim((string)($config['support_phone'] ?? '+49 1522 3649558'));
    $supportEmail = trim((string)($config['support_email'] ?? 'info@karvipartner.de'));
    $ref = contract_reference($contract);

    $body = '<p style="font-size:16px;line-height:1.7;color:#111114;margin:0 0 16px;">'
        . 'Vielen Dank für Ihre Registrierung bei <strong>Karvi Partner</strong>.'
        . '</p>'
        . '<p style="font-size:15px;line-height:1.7;color:#3b3b45;margin:0 0 16px;">'
        . 'Ihre digitale Bestätigung für <strong>' . email_escape($brandLabel) . '</strong> wurde erfolgreich übermittelt'
        . ($restaurant !== '' ? ' für <strong>' . email_escape($restaurant) . '</strong>' : '')
        . '. Im Anhang finden Sie Ihr unterzeichnetes Registrierungsdokument als PDF.'
        . '</p>'
        . '<p style="font-size:15px;line-height:1.7;color:#3b3b45;margin:0 0 16px;">'
        . 'Wir freuen uns auf die Zusammenarbeit und melden uns bei Ihnen, sobald die nächsten Schritte für die Einrichtung starten.'
        . '</p>'
        . email_info_table([
            'Referenz' => $ref,
            'Bestätigt am' => format_date($signedAt) . ' ' . substr($signedAt, 11),
            'Marke' => $brandLabel,
        ])
        . '<div style="margin-top:24px;padding:18px;background:#f7f7f9;border-radius:14px;border:1px solid #ececee;">'
        . '<div style="font-size:14px;font-weight:700;color:#111114;margin-bottom:8px;">Fragen oder Rückmeldung?</div>'
        . '<p style="font-size:14px;line-height:1.7;color:#3b3b45;margin:0;">'
        . 'Für weitere Anfragen erreichen Sie uns jederzeit telefonisch unter '
        . '<a href="tel:' . email_escape(preg_replace('/\s+/', '', $supportPhone) ?? $supportPhone) . '" style="color:#111114;font-weight:700;">'
        . email_escape($supportPhone)
        . '</a>'
        . ' oder per E-Mail an '
        . '<a href="mailto:' . email_escape($supportEmail) . '" style="color:#111114;font-weight:700;">'
        . email_escape($supportEmail)
        . '</a>.'
        . '</p>'
        . '</div>';

    return [
        'subject' => 'Vielen Dank – Ihre Registrierung bei Karvi Partner',
        'html' => email_layout('Registrierung bestätigt', $body),
    ];
}

function contract_build_admin_registration_email(
    array $contract,
    array $auditRecords,
    string $signedAt,
    string $customerEmail
): array {
    $brandLabel = contract_brand_display_label($contract);
    $ref = contract_reference($contract);
    $restaurant = trim((string)($contract['restaurant_name'] ?? $contract['partner_name'] ?? ''));

    $fieldLabels = [
        'field_restaurant_name' => 'Restaurantname',
        'field_brand' => 'Marke',
        'field_contract_date' => 'Datum',
        'field_legal_name' => 'Gesetzlicher Name / Firmierung',
        'field_owner_name' => 'Inhaber / Geschäftsführer',
        'field_contact_person' => 'Kontaktperson',
        'field_company_phone' => 'Telefon',
        'field_contact_mobile' => 'Mobilnummer',
        'field_street' => 'Straße',
        'field_postal_city' => 'PLZ und Ort',
        'field_country' => 'Land',
        'field_vat_id' => 'USt-IdNr.',
        'field_tax_number' => 'Steuernummer',
    ];

    $summaryRows = [];
    foreach (registration_summary_rows($contract) as $labelKey => $value) {
        $summaryRows[$fieldLabels[$labelKey] ?? str_replace('field_', '', $labelKey)] = $value;
    }

    if ($customerEmail !== '') {
        $summaryRows['Registrierungs-E-Mail'] = $customerEmail;
    }

    $linkLocation = contract_link_location($contract);
    if ($linkLocation !== null) {
        $locationRows = location_audit_fields($linkLocation);
        if (!empty($locationRows['full_address'])) {
            $summaryRows['Standort (Link-Zugriff)'] = (string)$locationRows['full_address'];
        }
        if (!empty($locationRows['latitude']) && !empty($locationRows['longitude'])) {
            $summaryRows['Koordinaten'] = (string)$locationRows['latitude'] . ', ' . (string)$locationRows['longitude'];
        }
    }

    $auditHtml = '';
    foreach ($auditRecords as $index => $record) {
        if (is_array($record)) {
            $auditHtml .= email_audit_block($record, (int)$index);
        }
    }

    $body = '<p style="font-size:15px;line-height:1.7;color:#3b3b45;margin:0 0 18px;">'
        . 'Eine neue Partner-Registrierung wurde digital abgeschlossen. Alle Unterlagen und Audit-Daten finden Sie unten sowie im Anhang.'
        . '</p>'
        . '<div style="margin-bottom:22px;padding:16px 18px;background:#111114;border-radius:14px;color:#ffffff;">'
        . '<div style="font-size:12px;letter-spacing:0.08em;text-transform:uppercase;color:#b8b8c2;">Neue Registrierung</div>'
        . '<div style="font-size:20px;font-weight:700;margin-top:6px;">' . email_escape($restaurant !== '' ? $restaurant : $ref) . '</div>'
        . '<div style="font-size:14px;color:#d7d7de;margin-top:6px;">' . email_escape($brandLabel) . ' · ' . email_escape($ref) . '</div>'
        . '</div>'
        . '<div style="font-size:16px;font-weight:700;color:#111114;margin:0 0 12px;">Partnerangaben</div>'
        . email_info_table($summaryRows)
        . '<div style="font-size:16px;font-weight:700;color:#111114;margin:24px 0 12px;">Digitale Bestätigung &amp; Audit</div>'
        . ($auditHtml !== '' ? $auditHtml : '<p style="color:#6b6b76;">Keine Audit-Daten verfügbar.</p>')
        . '<p style="font-size:13px;line-height:1.6;color:#6b6b76;margin:0;">'
        . 'Anhänge: unterzeichnetes PDF und alle Unterschriften als PNG.'
        . '</p>';

    $subjectRestaurant = $restaurant !== '' ? $restaurant : $ref;

    return [
        'subject' => 'Neue Registrierung: ' . $subjectRestaurant,
        'html' => email_layout('Neue Partner-Registrierung', $body),
    ];
}

function contract_collect_signature_files(array $contract): array
{
    $config = app_config();
    $files = [];
    $signatures = api_get_signatures_for_contract_record($contract);

    foreach ($signatures as $index => $signature) {
        $imageName = basename((string)($signature['signature_image'] ?? ''));
        if ($imageName === '') {
            continue;
        }

        $path = $config['signatures_dir'] . '/' . $imageName;
        if (!is_file($path)) {
            continue;
        }

        $files[] = [
            'path' => $path,
            'filename' => contract_reference($contract) . '_signature_' . ($index + 1) . '.png',
            'content_id' => 'signature-' . $index,
            'inline' => true,
        ];
    }

    if ($files !== []) {
        return $files;
    }

    foreach (contract_all_tokens($contract) as $token) {
        foreach (glob($config['signatures_dir'] . '/' . $token . '_*') ?: [] as $path) {
            if (!is_file($path)) {
                continue;
            }

            $files[] = [
                'path' => $path,
                'filename' => contract_reference($contract) . '_signature_' . (count($files) + 1) . '.png',
                'content_id' => 'signature-' . count($files),
                'inline' => true,
            ];
        }
    }

    return $files;
}

function contract_send_registration_emails(array $contract, array $context): array
{
    $result = [
        'enabled' => email_is_enabled(),
        'customer' => null,
        'admin' => null,
        'skipped' => false,
    ];

    if (!email_is_enabled()) {
        $result['skipped'] = true;
        $result['reason'] = 'Email service disabled';

        return $result;
    }

    if (!empty($contract['registration_emails_sent_at'])) {
        $result['skipped'] = true;
        $result['reason'] = 'Already sent';

        return $result;
    }

    $signedPdfPath = (string)($context['signed_pdf_path'] ?? '');
    if ($signedPdfPath === '' || !is_file($signedPdfPath)) {
        $resolved = contract_resolve_signed_pdf_disk_path($contract);
        $signedPdfPath = $resolved ?? '';
    }

    if ($signedPdfPath === '' || !is_file($signedPdfPath)) {
        throw new RuntimeException('Signed PDF not found for email attachment.');
    }

    $signedAt = (string)($context['signed_at'] ?? $contract['signed_at'] ?? date('Y-m-d H:i:s'));
    $auditRecords = is_array($context['audit_records'] ?? null) ? $context['audit_records'] : [];
    $linkLocation = contract_link_location($contract);

    if ($linkLocation !== null) {
        foreach ($auditRecords as $index => $record) {
            if (!is_array($record)) {
                continue;
            }

            foreach (location_audit_fields($linkLocation) as $key => $value) {
                if (!isset($record[$key]) || $record[$key] === '' || $record[$key] === null) {
                    $auditRecords[$index][$key] = $value;
                }
            }
        }
    }
    $brandLabel = contract_brand_display_label($contract);
    $customerEmail = contract_registration_recipient_email($contract);
    $config = email_config();
    $adminEmail = trim((string)($config['admin_notification_email'] ?? 'info@karvipartner.de'));
    $replyTo = trim((string)($config['reply_to'] ?? $adminEmail));
    $pdfFilename = contract_reference($contract) . '_signed.pdf';

    if ($customerEmail !== '') {
        $customerMessage = contract_build_customer_registration_email($contract, $brandLabel, $signedAt);
        $customerAttachments = [];
        $pdfAttachment = resend_file_attachment($signedPdfPath, $pdfFilename);
        if ($pdfAttachment !== null) {
            $customerAttachments[] = $pdfAttachment;
        }

        try {
            $customerResponse = resend_send_email([
                'from' => resend_build_from(),
                'to' => [$customerEmail],
                'reply_to' => $replyTo !== '' ? $replyTo : 'info@karvipartner.de',
                'subject' => $customerMessage['subject'],
                'html' => $customerMessage['html'],
                'attachments' => $customerAttachments,
            ]);

            $result['customer'] = [
                'success' => true,
                'to' => $customerEmail,
                'id' => $customerResponse['id'] ?? null,
            ];
        } catch (Throwable $e) {
            $result['customer'] = [
                'success' => false,
                'to' => $customerEmail,
                'error' => $e->getMessage(),
            ];
        }
    } else {
        $result['customer'] = [
            'success' => false,
            'skipped' => true,
            'reason' => 'No customer email provided',
        ];
    }

    $adminMessage = contract_build_admin_registration_email($contract, $auditRecords, $signedAt, $customerEmail);
    $adminAttachments = [];
    $pdfAttachment = resend_file_attachment($signedPdfPath, $pdfFilename);
    if ($pdfAttachment !== null) {
        $adminAttachments[] = $pdfAttachment;
    }

    foreach (contract_collect_signature_files($contract) as $signatureFile) {
        $attachment = resend_file_attachment(
            $signatureFile['path'],
            $signatureFile['filename'],
            !empty($signatureFile['inline']) ? (string)$signatureFile['content_id'] : null
        );

        if ($attachment !== null) {
            $adminAttachments[] = $attachment;
        }
    }

    try {
        $adminResponse = resend_send_email([
            'from' => resend_build_from(),
            'to' => [$adminEmail],
            'reply_to' => $replyTo !== '' ? $replyTo : 'info@karvipartner.de',
            'subject' => $adminMessage['subject'],
            'html' => $adminMessage['html'],
            'attachments' => $adminAttachments,
        ]);

        $result['admin'] = [
            'success' => true,
            'to' => $adminEmail,
            'id' => $adminResponse['id'] ?? null,
        ];
    } catch (Throwable $e) {
        $result['admin'] = [
            'success' => false,
            'to' => $adminEmail,
            'error' => $e->getMessage(),
        ];
    }

    $adminOk = !empty($result['admin']['success']);

    if ($adminOk) {
        $token = contract_admin_token($contract);
        if ($token !== '') {
            local_store_update($token, [
                'registration_emails_sent_at' => date('Y-m-d H:i:s'),
                'registration_email_log' => $result,
            ]);
        }
    }

    return $result;
}
