<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\Database;
use Throwable;

class RegistrationEmailService
{
    public function sendConfirmation(
        array $delegate,
        array $event
    ): bool {
        $mailService = new MailService();

        $subject = 'Registration Confirmed: '
            . ($event['short_name']
                ?? 'Traditional Authorities Conference 2026');

        $logoPath = PUBLIC_PATH
            . '/assets/images/linkage-logo.jpg';

        $qrAbsolutePath = null;

        if (!empty($delegate['qr_code_path'])) {
            $qrAbsolutePath = PUBLIC_PATH
                . '/uploads/'
                . ltrim(
                    $delegate['qr_code_path'],
                    '/'
                );
        }

        $html = $this->buildConfirmationEmail(
            $delegate,
            $event,
            is_file($logoPath),
            $qrAbsolutePath !== null
                && is_file($qrAbsolutePath)
        );

        $embeddedImages = [];

        if (is_file($logoPath)) {
            $embeddedImages[] = [
                'path' => $logoPath,
                'cid' => 'linkage-logo',
                'name' => 'linkage-logo.jpg',
            ];
        }

        if (
            $qrAbsolutePath !== null &&
            is_file($qrAbsolutePath)
        ) {
            $embeddedImages[] = [
                'path' => $qrAbsolutePath,
                'cid' => 'delegate-qr',
                'name' => 'delegate-qr.png',
            ];
        }

        $attachments = [];

        if (
            $qrAbsolutePath !== null &&
            is_file($qrAbsolutePath)
        ) {
            $attachments[] = [
                'path' => $qrAbsolutePath,
                'name' =>
                    $delegate['registration_number']
                    . '-QR-Code.png',
            ];
        }

        $plainText = $this->buildPlainText(
            $delegate,
            $event
        );

        $emailLogId = $this->createEmailLog(
            $delegate,
            $event,
            $subject,
            $html
        );

        try {
            $result = $mailService->send(
                $delegate['email'],
                $delegate['full_names'],
                $subject,
                $html,
                $plainText,
                $attachments,
                $embeddedImages
            );

            $this->updateEmailLog(
                $emailLogId,
                $result
            );

            Database::execute(
                "
                UPDATE delegates
                SET email_status = :email_status
                WHERE id = :id
                ",
                [
                    'email_status' =>
                        $result['success']
                            ? 'sent'
                            : 'failed',
                    'id' => $delegate['id'],
                ]
            );

            return (bool) $result['success'];
        } catch (Throwable $exception) {
            $this->updateEmailLog(
                $emailLogId,
                [
                    'success' => false,
                    'message_id' => null,
                    'error' =>
                        $exception->getMessage(),
                ]
            );

            Database::execute(
                "
                UPDATE delegates
                SET email_status = 'failed'
                WHERE id = :id
                ",
                [
                    'id' => $delegate['id'],
                ]
            );

            error_log(
                'Registration email failed: '
                . $exception->getMessage()
            );

            return false;
        }
    }

    private function buildConfirmationEmail(
        array $delegate,
        array $event,
        bool $hasLogo,
        bool $hasQr
    ): string {
        $delegateName = e(
            $delegate['full_names']
        );

        $registrationNumber = e(
            $delegate['registration_number']
        );

        $eventName = e(
            $event['name']
            ?? '2nd Provincial Conference of Traditional Authorities, Government and Industry on Bridging the Digital Divide'
        );

        $statusMessage =
            ($delegate['registration_status']
                ?? 'approved') === 'pending'
                ? 'Your registration has been received and is awaiting approval.'
                : 'Your registration has been successfully confirmed.';

        $logo = $hasLogo
            ? '<img src="cid:linkage-logo" alt="Linkage SA Group" style="display:block;max-width:260px;height:auto;margin:0 auto;">'
            : '<div style="font-size:28px;font-weight:700;color:#3f8f2f;">Linkage SA Group</div>';

        $qr = $hasQr
            ? '
                <div style="text-align:center;margin:30px 0;">
                    <img
                        src="cid:delegate-qr"
                        alt="Delegate QR code"
                        style="display:block;width:190px;height:190px;margin:0 auto 12px;"
                    >
                    <p style="margin:0;color:#687269;font-size:13px;">
                        Present this QR code at the registration desk.
                    </p>
                </div>
            '
            : '';

        return '
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Registration Confirmation</title>
        </head>
        <body style="margin:0;padding:0;background:#f4f8f4;font-family:Arial,Helvetica,sans-serif;color:#27352c;">
            <table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="background:#f4f8f4;padding:30px 12px;">
                <tr>
                    <td align="center">
                        <table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="max-width:680px;background:#ffffff;border-radius:20px;overflow:hidden;box-shadow:0 14px 40px rgba(20,80,43,0.10);">
                            <tr>
                                <td style="padding:28px;text-align:center;border-top:8px solid #3f8f2f;">
                                    ' . $logo . '
                                </td>
                            </tr>

                            <tr>
                                <td style="padding:38px 38px 22px;text-align:center;background:linear-gradient(135deg,#0e4227,#3f8f2f);color:#ffffff;">
                                    <div style="font-size:12px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:#d7ed7b;">
                                        Registration Confirmation
                                    </div>

                                    <h1 style="margin:12px 0 8px;font-size:31px;line-height:1.2;">
                                        Thank you, ' . $delegateName . '
                                    </h1>

                                    <p style="margin:0;color:rgba(255,255,255,0.82);font-size:15px;line-height:1.6;">
                                        ' . e($statusMessage) . '
                                    </p>
                                </td>
                            </tr>

                            <tr>
                                <td style="padding:35px 38px;">
                                    <h2 style="margin:0 0 15px;color:#0e4227;font-size:20px;">
                                        ' . $eventName . '
                                    </h2>

                                    <table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:collapse;margin-top:20px;">
                                        <tr>
                                            <td style="padding:13px;background:#f2f8f1;border-bottom:1px solid #dce7dc;color:#687269;font-size:13px;">
                                                Registration Number
                                            </td>
                                            <td style="padding:13px;background:#f2f8f1;border-bottom:1px solid #dce7dc;text-align:right;font-weight:700;color:#0e4227;">
                                                ' . $registrationNumber . '
                                            </td>
                                        </tr>

                                        <tr>
                                            <td style="padding:13px;border-bottom:1px solid #e3eae4;color:#687269;font-size:13px;">
                                                Date
                                            </td>
                                            <td style="padding:13px;border-bottom:1px solid #e3eae4;text-align:right;font-weight:700;">
                                                23–24 July 2026
                                            </td>
                                        </tr>

                                        <tr>
                                            <td style="padding:13px;border-bottom:1px solid #e3eae4;color:#687269;font-size:13px;">
                                                Venue
                                            </td>
                                            <td style="padding:13px;border-bottom:1px solid #e3eae4;text-align:right;font-weight:700;">
                                                The Ranch Resort, Polokwane
                                            </td>
                                        </tr>

                                        <tr>
                                            <td style="padding:13px;color:#687269;font-size:13px;">
                                                Delegate Category
                                            </td>
                                            <td style="padding:13px;text-align:right;font-weight:700;">
                                                ' . e(
                                                    $delegate['category_name']
                                                    ?? 'Delegate'
                                                ) . '
                                            </td>
                                        </tr>
                                    </table>

                                    ' . $qr . '

                                    <div style="margin-top:28px;padding:18px;border-radius:13px;background:#eef8ef;border-left:5px solid #3f8f2f;">
                                        <strong style="display:block;color:#0e4227;margin-bottom:6px;">
                                            Important
                                        </strong>

                                        <p style="margin:0;color:#5f6e63;font-size:14px;line-height:1.6;">
                                            Please keep your registration number and QR code available on your mobile device when arriving at the conference.
                                        </p>
                                    </div>
                                </td>
                            </tr>

                            <tr>
                                <td style="padding:24px 38px;background:#092d20;color:rgba(255,255,255,0.78);font-size:13px;line-height:1.6;text-align:center;">
                                    <strong style="display:block;color:#ffffff;">
                                        Linkage SA Group (Pty) Ltd
                                    </strong>

                                    +27 74 462 8633<br>
                                    charley@linkagegroup.co.za
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>';
    }

    private function buildPlainText(
        array $delegate,
        array $event
    ): string {
        return
            "REGISTRATION CONFIRMATION\n\n"
            . "Dear {$delegate['full_names']},\n\n"
            . "Your registration for "
            . ($event['name']
                ?? 'the Traditional Authorities Conference')
            . " has been received.\n\n"
            . "Registration Number: "
            . $delegate['registration_number']
            . "\n"
            . "Date: 23–24 July 2026\n"
            . "Venue: The Ranch Resort, Polokwane\n\n"
            . "Please present your QR code at the registration desk.\n\n"
            . "Regards,\n"
            . "Linkage SA Group\n"
            . "+27 74 462 8633\n"
            . "charley@linkagegroup.co.za";
    }

    private function createEmailLog(
        array $delegate,
        array $event,
        string $subject,
        string $html
    ): int {
        return Database::insert(
            "
            INSERT INTO email_logs (
                event_id,
                delegate_id,
                recipient_name,
                recipient_email,
                subject,
                body_html,
                email_type,
                status,
                queued_at,
                created_at,
                updated_at
            ) VALUES (
                :event_id,
                :delegate_id,
                :recipient_name,
                :recipient_email,
                :subject,
                :body_html,
                'registration_confirmation',
                'queued',
                NOW(),
                NOW(),
                NOW()
            )
            ",
            [
                'event_id' => $event['id'],
                'delegate_id' => $delegate['id'],
                'recipient_name' =>
                    $delegate['full_names'],
                'recipient_email' =>
                    $delegate['email'],
                'subject' => $subject,
                'body_html' => $html,
            ]
        );
    }

    private function updateEmailLog(
        int $emailLogId,
        array $result
    ): void {
        Database::execute(
            "
            UPDATE email_logs
            SET
                status = :status,
                provider_message_id =
                    :provider_message_id,
                error_message = :error_message,
                sent_at = :sent_at,
                failed_at = :failed_at,
                updated_at = NOW()
            WHERE id = :id
            ",
            [
                'status' =>
                    $result['success']
                        ? 'sent'
                        : 'failed',
                'provider_message_id' =>
                    $result['message_id'],
                'error_message' =>
                    $result['error'],
                'sent_at' =>
                    $result['success']
                        ? date('Y-m-d H:i:s')
                        : null,
                'failed_at' =>
                    !$result['success']
                        ? date('Y-m-d H:i:s')
                        : null,
                'id' => $emailLogId,
            ]
        );
    }
}