<?php
/**
 * ════════════════════════════════════════════════════════════════
 * CWC EVENT — Complete Email Service (All Email Touchpoints)
 * Amazon SES · ap-south-1 · No SDK required
 * ════════════════════════════════════════════════════════════════
 *
 * USAGE — include this file anywhere and call:
 *
 *  require_once 'cwc_emails.php';
 *  $emailer = new CwcEmailer();
 *
 *  $emailer->sendOtp($email, $otp);
 *  $emailer->sendVvipInvite($email, $name, $company, $designation, $inviteUrl, $categoryName);
 *  $emailer->sendBulkInvite($email, $name, $company, $designation, $inviteUrl, $categoryName);
 *  $emailer->sendRegistrationReceived($email, $name, $regNo, $designation, $company);
 *  $emailer->sendRejection($email, $name, $reason);
 *  $emailer->sendApprovalWithQr($email, $name, $regNo, $designation, $company, $category, $qrToken, $eventDate, $venue);
 *  $emailer->sendReminder($email, $name, $regNo, $rsvpUrl, $eventDate, $venue);
 */

class CwcEmailer
{
    private string $key;
    private string $secret;
    private string $region;
    private string $from;
    private string $fromName;
    private string $eventName = 'Corporate World Cup';
    private string $eventDateLabel = '20 September 2026';
    private string $eventDateTime = 'Sunday, 20 September 2026 · 02:00 PM to 10:00 PM';
    private string $eventVenue = 'Radisson Gurgaon, Udyog Vihar, NCR';

    public function __construct(
        string $key = 'AKIA5B2DSPBTFZUQQ47T',
        string $secret = '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',
        string $region = 'ap-south-1',
        string $from = 'partners@corporateworldcup.com',
        string $fromName = 'Corporate World Cup'
    ) {
        $this->key = $key;
        $this->secret = $secret;
        $this->region = $region;
        $this->from = $from;
        $this->fromName = $fromName;
    }

    public function setEventConfig(array $labels): void
    {
        if (!empty($labels['name']))
            $this->eventName = (string) $labels['name'];
        if (!empty($labels['date']))
            $this->eventDateLabel = (string) $labels['date'];
        if (!empty($labels['date_time']))
            $this->eventDateTime = (string) $labels['date_time'];
        if (!empty($labels['venue']))
            $this->eventVenue = (string) $labels['venue'];
    }

    // ────────────────────────────────────────────────────────────
    // 1. OTP EMAIL
    // ────────────────────────────────────────────────────────────
    public function sendOtp(string $toEmail, string $otp, string $eventName = 'Corporate World Cup'): array
    {
        $subject = "Your {$eventName} Verification Code: {$otp}";
        $html = $this->tplOtp($otp, $eventName);
        $text = "Your CWC verification code is: {$otp}\n\nExpires in 5 minutes. Do not share this code.";
        return $this->send($toEmail, $subject, $html, $text);
    }

    // ────────────────────────────────────────────────────────────
    // 2. VVIP INVITE EMAIL
    // ────────────────────────────────────────────────────────────
    public function sendVvipInvite(string $toEmail, string $name, string $company, string $designation, string $inviteUrl, string $categoryName = 'VVIP Guest'): array
    {
        $subject = "You're Personally Invited — {$this->eventName} · {$this->eventDateLabel}";
        $html = $this->tplVvipInvite($name, $company, $designation, $inviteUrl, $categoryName);
        $text = "Dear {$name},\n\nYou are personally invited to {$this->eventName}.\n\nEvent: {$this->eventDateTime}\nVenue: {$this->eventVenue}\n\nYour invitation link:\n{$inviteUrl}\n\nCorporate World Cup Team";
        return $this->send($toEmail, $subject, $html, $text);
    }

    // ────────────────────────────────────────────────────────────
    // 3. BULK INVITE EMAIL
    // ────────────────────────────────────────────────────────────
    public function sendBulkInvite(string $toEmail, string $name, string $company, string $designation, string $inviteUrl, string $categoryName = 'Corporate Guest'): array
    {
        $subject = "Invitation: {$this->eventName} · {$this->eventDateLabel}";
        $html = $this->tplBulkInvite($name, $company, $designation, $inviteUrl, $categoryName);
        $text = "Dear {$name},\n\nYou are invited to {$this->eventName}.\n\nEvent: {$this->eventDateTime}\nVenue: {$this->eventVenue}\n\nRegister here:\n{$inviteUrl}\n\nCorporate World Cup Team";
        return $this->send($toEmail, $subject, $html, $text);
    }

    // ────────────────────────────────────────────────────────────
    // 4. REGISTRATION RECEIVED
    // ────────────────────────────────────────────────────────────
    public function sendRegistrationReceived(string $toEmail, string $name, string $regNo, string $designation = '', string $company = ''): array
    {
        $subject = "Registration Received — {$name}, We Have Your Details";
        $html = $this->tplRegistrationReceived($name, $regNo, $designation, $company);
        $text = "Dear {$name},\n\nYour registration {$regNo} has been received and is pending approval.\n\nEvent: {$this->eventDateTime}\nVenue: {$this->eventVenue}\n\nCorporate World Cup Team";
        return $this->send($toEmail, $subject, $html, $text);
    }

    // ────────────────────────────────────────────────────────────
    // 5. REJECTION EMAIL
    // ────────────────────────────────────────────────────────────
    public function sendRejection(string $toEmail, string $name, string $reason = 'We were unable to accommodate your registration at this time.'): array
    {
        $subject = "Update on Your Corporate World Cup Registration";
        $html = $this->tplRejection($name, $reason);
        $text = "Dear {$name},\n\nThank you for your interest in Corporate World Cup.\n\nUnfortunately, we are unable to approve your registration at this time.\n\nReason: {$reason}\n\nFor queries, contact: partners@corporateworldcup.com";
        return $this->send($toEmail, $subject, $html, $text);
    }

    // ────────────────────────────────────────────────────────────
    // 6. APPROVAL + QR CREDENTIAL EMAIL
    // ────────────────────────────────────────────────────────────
    public function sendApprovalWithQr(string $toEmail, string $name, string $regNo, string $designation, string $company, string $category, string $qrToken, string $eventDate = '', string $venue = '', array $nominations = []): array
    {
        $eventDate = $eventDate ?: $this->eventDateTime;
        $venue = $venue ?: $this->eventVenue;
        $subjectName = trim((string) preg_replace('/\s+/', ' ', $name));
        if ($subjectName === '')
            $subjectName = 'Guest';
        $subject = "{$subjectName}, You're Approved — Your CWC Event Credential is Ready";
        $html = $this->tplApprovalWithQr($name, $regNo, $designation, $company, $category, $qrToken, $eventDate, $venue, $nominations);
        $text = "Dear {$name},\n\nCongratulations! Your registration {$regNo} has been approved.\n\nEvent: {$eventDate} | {$venue}\nCategory: {$category}\nCredential: {$regNo}";
        foreach ($nominations as $nomination) {
            $nomination = (array) $nomination;
            $award = trim((string) ($nomination['award_title'] ?? 'PCL Legacy Recognition'));
            $by = trim((string) ($nomination['nominator_name'] ?? $nomination['nominator_name_snapshot'] ?? ''));
            $reason = trim((string) ($nomination['nomination_reason'] ?? ''));
            $text .= "\n\nNominated Player Recognition: {$award}" . ($by !== '' ? "\nNominated by: {$by}" : '') . ($reason !== '' ? "\nWhy nominated: {$reason}" : '');
        }
        $text .= "\n\nPresent this email or your QR code at the venue.\n\nCorporate World Cup Team";
        return $this->send($toEmail, $subject, $html, $text);
    }

    // ────────────────────────────────────────────────────────────
    // 7. EVENT REMINDER EMAIL
    // ────────────────────────────────────────────────────────────
    public function sendReminder(string $toEmail, string $name, string $regNo, string $credentialUrl, string $eventDate = '', string $venue = '', string $reportingTime = ''): array
    {
        $eventDate = $eventDate ?: $this->eventDateTime;
        $venue = $venue ?: $this->eventVenue;
        $reportingTime = $reportingTime ?: '01:30 PM';
        $subject = "Reminder: Corporate World Cup is Tomorrow — {$eventDate}";
        $html = $this->tplReminder($name, $regNo, $credentialUrl, $eventDate, $venue, $reportingTime);
        $text = "Dear {$name},\n\nThis is a reminder for Corporate World Cup on {$eventDate} at {$venue}.\n\nYour Registration: {$regNo}\n\nCorporate World Cup Team";
        return $this->send($toEmail, $subject, $html, $text);
    }

    public function sendAttendanceConfirmation(string $toEmail, string $action, string $name, string $regNo, string $timestamp, string $gate, string $venue, string $venueMapUrl, string $scanMapUrl): array
    {
        $isCheckin = strtoupper($action) === 'CHECKIN';
        $label = $isCheckin ? 'Checked In' : 'Checked Out';
        $subject = "{$label} — Corporate World Cup Attendance Confirmation";
        $scanLocation = $scanMapUrl === 'GPS unavailable' ? 'GPS was unavailable at the gate device.' : '<a href="' . $this->e($scanMapUrl) . '" style="color:#9e6b20">View captured gate location</a>';
        $html = $this->emailWrap($this->sectionOpen() . $this->eyebrow('Attendance Confirmation') . $this->heading(($isCheckin ? '&#x2705; ' : '&#x1F6AA; ') . $label . ' successfully')
            . $this->para("Dear <strong style=\"color:#0e1c38\">{$this->e($name)}</strong>,<br><br>Your event attendance has been recorded successfully.")
            . $this->infoBox('Status', '<strong>' . $label . '</strong>') . $this->infoBox('Registration & Time', $this->e($regNo) . '<br>' . $this->e($timestamp) . '<br>' . $this->e($gate))
            . $this->infoBox('Venue', $this->e($venue) . '<br><a href="' . $this->e($venueMapUrl) . '" style="color:#9e6b20">Open venue in Google Maps</a>')
            . $this->infoBox('Gate Scan Location', $scanLocation) . $this->sectionClose());
        $text = "Dear {$name},\n\n{$label} successfully.\nRegistration: {$regNo}\nTime: {$timestamp}\nGate: {$gate}\nVenue: {$venue}\nVenue map: {$venueMapUrl}\nGate location: {$scanMapUrl}\n\nCorporate World Cup Team";
        return $this->send($toEmail, $subject, $html, $text);
    }

    public function sendLegacyNominationPending(string $toEmail, string $name, string $nominatorName, string $teamName, string $awardName, string $awardSubtitle, string $reason): array
    {
        $subject = $nominatorName . ' has nominated you for ' . $awardName . ' — Pending Approval';
        $html = $this->emailWrap(
            $this->sectionOpen()
            . $this->eyebrow('PCL Legacy Recognition · Pending Review')
            . $this->heading('You have been nominated')
            . $this->para('Dear <strong style="color:#0e1c38">' . $this->e($name) . '</strong>,<br><br><strong>' . $this->e($nominatorName) . '</strong> has nominated you for a PCL Legacy Recognition award.')
            . $this->infoBox('Recognition', $this->e($awardName) . '<br><span style="font-size:13px;font-weight:500">' . $this->e($awardSubtitle) . '</span>')
            . $this->infoBox('Nominated by', $this->e($nominatorName) . '<br>' . $this->e($teamName))
            . $this->infoBox('Why you were nominated', nl2br($this->e($reason)))
            . $this->infoBox('Status', '<span style="color:#95670d">Pending PCL Team Approval</span>')
            . $this->infoBox('Event details', $this->e($this->eventDateTime) . '<br>' . $this->e($this->eventVenue))
            . $this->para('No registration action is required yet. After the PCL Team approves this nomination, you will receive a separate secure email containing your registration link and event details.')
            . $this->sectionClose()
        );
        $text = "Dear {$name},\n\n{$nominatorName} ({$teamName}) has nominated you for {$awardName}.\n\nWhy: {$reason}\n\nStatus: Pending PCL Approval. Your registration link will be sent after approval.\n\nEvent: {$this->eventDateTime}\nVenue: {$this->eventVenue}";
        return $this->send($toEmail, $subject, $html, $text);
    }

    public function sendLegacyNomination(string $toEmail, string $name, string $nominatorName, string $teamName, string $awardName, string $awardSubtitle, string $nominationUrl, string $expiresAt = '13 September 2026', string $reason = ''): array
    {
        $subject = $nominatorName . ' nominated you — Approved to register for ' . $awardName;
        $html = $this->emailWrap(
            $this->sectionOpen()
            . $this->eyebrow('PCL Legacy Recognition · Official Nomination')
            . $this->heading('You have been nominated')
            . $this->para('Dear <strong style="color:#0e1c38">' . $this->e($name) . '</strong>,<br><br>Your contribution to the corporate cricket journey has been recognised by a fellow PCL player.')
            . '<div style="background:linear-gradient(135deg,#fff8e7,#fffdf8);border:1px solid #dfbf78;border-left:5px solid #aa741f;border-radius:14px;padding:20px;margin:22px 0">'
            . '<div style="font-size:11px;color:#90651e;font-weight:900;letter-spacing:1px;text-transform:uppercase">Selected Recognition</div>'
            . '<div style="font-size:20px;color:#0e1c38;font-weight:900;margin-top:7px;line-height:1.35">' . $this->e($awardName) . '</div>'
            . '<div style="font-size:13px;color:#685b45;margin-top:6px">' . $this->e($awardSubtitle) . '</div></div>'
            . $this->infoBox('Nominated by', $this->e($nominatorName) . '<br>' . $this->e($teamName))
            . ($reason !== '' ? $this->infoBox('Why you were nominated', nl2br($this->e($reason))) : '')
            . $this->infoBox('Status', '<span style="color:#176247">Approved — Registration Open</span>')
            . $this->infoBox('Event details', $this->e($this->eventDateTime) . '<br>' . $this->e($this->eventVenue))
            . $this->para('Open your secure link to review the nomination. Your PCL player and team details will be pre-filled in the existing event registration journey.')
            . $this->btn($nominationUrl, 'Review & Accept Nomination →')
            . '<p style="margin:18px 0 0;font-size:11px;color:#8a93a1">This personal link expires on <strong>' . $this->e($expiresAt) . '</strong>. Please do not forward it.</p>'
            . $this->sectionClose()
        );
        $text = "Dear {$name},\n\nYour nomination for {$awardName} ({$awardSubtitle}) by {$nominatorName}, {$teamName} has been approved.\n\nWhy: {$reason}\n\nEvent: {$this->eventDateTime}\nVenue: {$this->eventVenue}\n\nRegister here: {$nominationUrl}\n\nLink expires: {$expiresAt}.\n\nPCL Legacy Recognition 2026";
        return $this->send($toEmail, $subject, $html, $text);
    }

    public function sendBroadcast(string $toEmail, string $name, string $subject, string $message): array
    {
        $safeName = $this->e($name ?: 'Guest');
        $safeMessage = nl2br($this->e($message));
        $html = $this->emailWrap(
            $this->sectionOpen()
            . $this->eyebrow('Official Event Update')
            . $this->heading($this->e($subject))
            . $this->para("Dear <strong style=\"color:#0e1c38\">{$safeName}</strong>,")
            . '<div style="font-size:14px;color:#48546a;line-height:1.8">' . $safeMessage . '</div>'
            . $this->sectionClose()
        );
        return $this->send($toEmail, $subject, $html, "Dear {$name},\n\n{$message}\n\nCorporate World Cup 2026");
    }

    public function sendEventPostponed(string $toEmail, string $name, string $message): array
    {
        $subject = 'Important Update — Corporate World Cup Event Postponed';
        $safeName = $this->e($name ?: 'Guest');
        $safeMessage = nl2br($this->e($message));
        $html = $this->emailWrap(
            $this->sectionOpen()
            . $this->eyebrow('Important Event Update')
            . $this->heading('Corporate World Cup has been postponed')
            . $this->para("Dear <strong style=\"color:#0e1c38\">{$safeName}</strong>,")
            . '<div style="background:#fff8e8;border:1px solid #ead6a9;border-radius:14px;padding:18px 20px;margin-bottom:20px;font-size:14px;color:#5f4a20;line-height:1.8">' . $safeMessage . '</div>'
            . $this->para('No action is required from you. Your existing registration remains valid, and the organising team will share the revised schedule shortly.')
            . $this->sectionClose()
        );
        return $this->send($toEmail, $subject, $html, "Dear {$name},\n\n{$message}\n\nYour registration remains valid. Revised details will be shared shortly.\n\nCorporate World Cup 2026");
    }

    /**
     * Send an admin-authored HTML email to multiple recipients in one SES call.
     * Used by the Hall of Fame communication desk. Credentials remain server-side.
     */
    public function sendCustom(array $to, array $cc, string $subject, string $html, string $text = '', array $attachments = []): array
    {
        $normalise = static function (array $addresses): array {
            $valid = [];
            foreach ($addresses as $address) {
                $address = strtolower(trim((string) $address));
                if (filter_var($address, FILTER_VALIDATE_EMAIL)) $valid[$address] = $address;
            }
            return array_values($valid);
        };

        $to = $normalise($to);
        $cc = $normalise(array_merge($cc, [
            'pcl@procorporateleague.com',
            'sachin.gupta@corporateworldcup.com',
            'sachin.gupta@procorporateleague.com',
        ]));
        $cc = array_values(array_diff($cc, $to));
        if (empty($to)) return ['success' => false, 'error' => 'At least one valid TO email is required'];
        if (count($to) + count($cc) > 50) return ['success' => false, 'error' => 'Amazon SES allows a maximum of 50 total TO and CC recipients per send'];
        if ($subject === '' || $html === '') return ['success' => false, 'error' => 'Subject and HTML message are required'];
        if ($text === '') $text = trim(html_entity_decode(strip_tags(preg_replace('/<br\s*\/?>/i', "\n", $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8'));

        $result = $this->sendSes($to, $cc, $subject, $html, $text, $attachments);
        $result['to_count'] = count($to);
        $result['cc_count'] = count($cc);
        $result['attachments_count'] = count($attachments);
        return $result;
    }

    // ════════════════════════════════════════════════════════════
    // SES SEND (AWS Signature V4 — No SDK)
    // ════════════════════════════════════════════════════════════
    private function send(string $to, string $subj, string $html, string $text): array
    {
        $ccList = array_values(array_filter(
            ['pcl@procorporateleague.com', 'sachin.gupta@corporateworldcup.com'],
            function ($cc) use ($to) {
                return strtolower(trim($cc)) !== strtolower(trim($to));
            }
        ));
        return $this->sendSes([$to], $ccList, $subj, $html, $text);
    }

    private function sendSes(array $to, array $cc, string $subj, string $html, string $text, array $attachments = []): array
    {
        $date = gmdate('Ymd\THis\Z');
        $sd = gmdate('Ymd');
        $host = "email.{$this->region}.amazonaws.com";
        $url = "https://{$host}/v2/email/outbound-emails";

        $destination = ['ToAddresses' => array_values($to)];
        if (!empty($cc)) {
            $destination['CcAddresses'] = array_values($cc);
        }

        $sesAttachments = [];
        foreach ($attachments as $a) {
            if (!is_array($a)) continue;
            $sesAttachments[] = [
                'FileName'=>(string)($a['filename'] ?? 'attachment'),
                'RawContent'=>(string)($a['content_base64'] ?? ''),
                'ContentDisposition'=>'ATTACHMENT',
                'ContentDescription'=>(string)($a['filename'] ?? 'attachment'),
                'ContentTransferEncoding'=>'BASE64',
                'ContentType'=>(string)($a['mime'] ?? 'application/octet-stream'),
            ];
        }
        $simple = [
            'Subject' => ['Data' => $subj, 'Charset' => 'UTF-8'],
            'Body' => [
                'Html' => ['Data' => $html, 'Charset' => 'UTF-8'],
                'Text' => ['Data' => $text, 'Charset' => 'UTF-8'],
            ],
        ];
        if ($sesAttachments) $simple['Attachments'] = $sesAttachments;
        $body = json_encode([
            'FromEmailAddress' => "{$this->fromName} <{$this->from}>",
            'Destination' => $destination,
            'ReplyToAddresses' => [$this->from],
            'Content' => [
                'Simple' => $simple
            ],
        ]);


        $hash = hash('sha256', $body);
        $ch = "content-type:application/json\nhost:{$host}\nx-amz-date:{$date}\n";
        $sh = 'content-type;host;x-amz-date';
        $cr = "POST\n/v2/email/outbound-emails\n\n{$ch}\n{$sh}\n{$hash}";
        $scope = "{$sd}/{$this->region}/ses/aws4_request";
        $sts = "AWS4-HMAC-SHA256\n{$date}\n{$scope}\n" . hash('sha256', $cr);
        $sk = $this->hm($this->hm($this->hm($this->hm('AWS4' . $this->secret, $sd), $this->region), 'ses'), 'aws4_request');
        $sig = hash_hmac('sha256', $sts, $sk);
        $auth = "AWS4-HMAC-SHA256 Credential={$this->key}/{$scope}, SignedHeaders={$sh}, Signature={$sig}";

        $c = curl_init($url);
        curl_setopt_array($c, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "Host: {$host}",
                "X-Amz-Date: {$date}",
                "Authorization: {$auth}",
            ],
        ]);
        $resp = curl_exec($c);
        $code = curl_getinfo($c, CURLINFO_HTTP_CODE);
        $err = curl_error($c);
        curl_close($c);
        if ($err)
            return ['success' => false, 'error' => $err];
        $j = json_decode($resp, true);
        return $code >= 200 && $code < 300
            ? ['success' => true, 'message_id' => $j['MessageId'] ?? '']
            : ['success' => false, 'error' => $j['message'] ?? "HTTP {$code}", 'raw' => $resp];
    }

    private function hm(string $key, string $data): string
    {
        return hash_hmac('sha256', $data, $key, true);
    }
    private function e(string $v): string
    {
        return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
    }

    // ════════════════════════════════════════════════════════════
    // SHARED LAYOUT HELPERS
    // ════════════════════════════════════════════════════════════
    private function emailWrap(string $bodyContent): string
    {
        return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">'
            . '<meta name="viewport" content="width=device-width,initial-scale=1">'
            . '<meta name="color-scheme" content="light dark"><meta name="supported-color-schemes" content="light dark">'
            . '</head>'
            . '<body style="margin:0;padding:0;background:#f5f4f0;font-family:Inter,-apple-system,BlinkMacSystemFont,\'Segoe UI\',sans-serif">'
            . '<table width="100%" cellpadding="0" cellspacing="0" style="background:#f5f4f0;padding:36px 16px">'
            . '<tr><td align="center">'
            . '<table width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:20px;overflow:hidden;box-shadow:0 8px 40px rgba(14,28,56,.10);border:1px solid rgba(173,121,40,.18)">'
            . $this->header()
            . $bodyContent
            . $this->footer()
            . '</table>'
            . '</td></tr></table></body></html>';
    }

    private function header(): string
    {
        return '<tr><td style="height:3px;background:linear-gradient(90deg,transparent,#9e6b20,#efd08b,#9e6b20,transparent)"></td></tr>'
            . '<tr><td style="background:linear-gradient(135deg,#0e1c38,#1b3158);padding:24px 32px;text-align:center">'
            . '<table cellpadding="0" cellspacing="0" border="0" align="center" style="margin:0 auto 14px auto">'
            . '<tr><td style="padding:0;text-align:center">'
            . '<a href="https://www.procorporateleague.com" target="_blank" style="text-decoration:none;display:inline-block">'
            . '<img src="https://launch.corporateworldcup.com/_api/assets/pcl-logo-light.png?v=20260910-1" alt="PRO CORPORATE LEAGUE" width="190" height="74" style="display:block;width:190px;max-width:100%;height:auto;border:0;outline:none;color:#ffffff;font-size:14px;font-weight:900" />'
            . '</a>'
            . '</td></tr></table>'
            . '<div style="color:#d4af37;font-size:11px;letter-spacing:2.5px;font-weight:800;text-transform:uppercase">CORPORATE WORLD CUP</div>'
            . '<div style="color:#d4af37;font-size:11.5px;margin-top:3px;letter-spacing:.5px;font-weight:600">' . $this->e($this->eventDateTime) . '<br>' . $this->e($this->eventVenue) . '</div>'
            . '</td></tr>';
    }


    private function footer(): string
    {
        return '<tr><td style="border-top:1px solid #ede8df;padding:16px 36px;background:#fffdf9;text-align:center">'
            . '<p style="margin:0;font-size:11px;color:#9aa3b0;line-height:1.8">'
            . 'Corporate World Cup &middot; Gurgaon, NCR 2026<br>'
            . '<a href="mailto:partners@corporateworldcup.com" style="color:#9e6b20;text-decoration:none">partners@corporateworldcup.com</a>'
            . '</p></td></tr>';
    }

    private function sectionOpen(string $style = 'padding:36px'): string
    {
        return "<tr><td style=\"{$style}\">";
    }

    private function sectionClose(): string
    {
        return '</td></tr>';
    }

    private function eyebrow(string $text): string
    {
        return "<div style=\"font-size:10px;letter-spacing:2px;text-transform:uppercase;color:#8d6924;font-weight:800;margin-bottom:10px\">{$text}</div>";
    }

    private function heading(string $text): string
    {
        return "<h1 style=\"margin:0 0 8px;font-size:26px;font-weight:500;color:#0e1c38;font-family:Georgia,'Times New Roman',serif;line-height:1.2\">{$text}</h1>";
    }

    private function para(string $text): string
    {
        return "<p style=\"margin:0 0 20px;color:#6d778b;font-size:14px;line-height:1.75\">{$text}</p>";
    }

    private function infoBox(string $label, string $value): string
    {
        return '<table cellpadding="0" cellspacing="0" style="background:#fffdf8;border:1px solid #ebe4d7;border-radius:14px;padding:14px 20px;width:100%;margin-bottom:14px">'
            . "<tr><td style=\"font-size:10px;color:#8d6924;letter-spacing:1.5px;text-transform:uppercase;font-weight:800\">{$label}</td></tr>"
            . "<tr><td style=\"font-size:16px;font-weight:800;color:#0e1c38;padding-top:4px\">{$value}</td></tr>"
            . '</table>';
    }

    private function btn(string $url, string $label, bool $gold = true): string
    {
        $bg = $gold
            ? 'background:linear-gradient(105deg,#92621b,#d6ae61,#92621b);color:#fff'
            : 'background:linear-gradient(135deg,#0e1c38,#1b3158);color:#fff';
        return "<table cellpadding=\"0\" cellspacing=\"0\" style=\"margin:20px 0\"><tr>"
            . "<td style=\"{$bg};border-radius:12px;padding:13px 28px;font-weight:800;font-size:14px;letter-spacing:.3px;display:block\">"
            . "<a href=\"{$url}\" style=\"color:#fff;text-decoration:none;display:block\">{$label}</a>"
            . "</td></tr></table>";
    }

    private function badge(string $text, string $color = '#edf8f3', string $textColor = '#116347'): string
    {
        return "<span style=\"display:inline-block;background:{$color};color:{$textColor};border-radius:999px;padding:5px 12px;font-size:10px;font-weight:900;letter-spacing:1px;text-transform:uppercase\">{$text}</span>";
    }

    // ════════════════════════════════════════════════════════════
    // EMAIL TEMPLATES
    // ════════════════════════════════════════════════════════════

    // ── 1. OTP ──────────────────────────────────────────────────
    private function tplOtp(string $otp, string $eventName): string
    {
        // Build digit table - always one row, never wraps
        $tds = '';
        foreach (str_split($otp) as $d) {
            $tds .= "<td style=\"width:38px;height:48px;text-align:center;vertical-align:middle;"
                . "font-size:24px;font-weight:900;background:#fffdf8;"
                . "border:1.5px solid #ddd0b3;border-radius:8px;"
                . "color:#0e1c38;font-family:ui-monospace,monospace;padding:0\">{$d}</td>";
        }
        $otpRow = '<table align="center" cellpadding="0" cellspacing="6" style="margin:0 auto 26px">'
            . "<tr>{$tds}</tr></table>";

        $body = $this->sectionOpen('padding:36px;text-align:center')
            . $this->eyebrow('Verification Code')
            . $this->heading('Confirm your identity')
            . $this->para('Enter the code below to verify your contact and complete your event registration.')
            . $otpRow
            . '<table align="center" cellpadding="0" cellspacing="0" style="margin:0 auto 22px"><tr>'
            . '<td style="background:#fffdf8;border:1px solid #ebe4d7;border-radius:12px;padding:12px 20px">'
            . '<span style="font-size:12px;color:#7c6a46">&#x23F1; Expires in <strong>5 minutes</strong></span>'
            . '</td></tr></table>'
            . '<p style="margin:0;font-size:11px;color:#9aa3b0">Do not share this code with anyone.</p>'
            . $this->sectionClose();

        return $this->emailWrap($body);
    }

    // ── 2. VVIP INVITE ──────────────────────────────────────────
    private function tplVvipInvite(string $name, string $company, string $designation, string $inviteUrl, string $categoryName): string
    {
        $body = $this->sectionOpen()
            . $this->eyebrow('Private Invitation')
            . $this->heading("Dear {$this->e($name)},")
            . $this->para("You have been personally selected and invited to <strong style=\"color:#0e1c38\">Corporate World Cup</strong> — an exclusive gathering of corporate leaders, players, and distinguished guests.")
            . $this->infoBox('Event', $this->e($this->eventDateTime) . '<br>' . $this->e($this->eventVenue))
            . $this->infoBox('Category Reserved For You', $this->e($categoryName))
            . $this->infoBox('Guest', $this->e($name) . ($company ? ' &middot; ' . $this->e($designation) . ', ' . $this->e($company) : ''))
            . '<div style="background:#fffdf8;border:1px solid #ebe4d7;border-radius:14px;padding:16px 20px;margin-bottom:20px">'
            . '<p style="margin:0;font-size:12px;color:#7c6a46;line-height:1.7">&#x1F511; This is a <strong>personalised, private link</strong> — for your use only. Do not share it. It will take you directly to your registration form with your details pre-filled.</p>'
            . '</div>'
            . $this->btn($inviteUrl, 'Confirm Your Invitation &rarr;')
            . '<p style="margin:0;font-size:11px;color:#9aa3b0">If the button above doesn\'t work, copy this link:<br><span style="color:#9e6b20;word-break:break-all">' . $this->e($inviteUrl) . '</span></p>'
            . $this->sectionClose();

        return $this->emailWrap($body);
    }

    // ── 3. BULK INVITE ──────────────────────────────────────────
    private function tplBulkInvite(string $name, string $company, string $designation, string $inviteUrl, string $categoryName): string
    {
        $body = $this->sectionOpen()
            . $this->eyebrow('Event Invitation')
            . $this->heading($this->e($this->eventName))
            . $this->para("Dear <strong style=\"color:#0e1c38\">{$this->e($name)}</strong>,<br><br>We are pleased to invite you to <strong>Corporate World Cup</strong>, a premier event bringing together top corporate teams for a landmark cricket experience.")
            . $this->infoBox('Date, Time & Venue', $this->e($this->eventDateTime) . '<br>' . $this->e($this->eventVenue))
            . $this->infoBox('Registration Category', $this->e($categoryName))
            . $this->btn($inviteUrl, 'Register for the Event &rarr;')
            . '<p style="margin:16px 0 0;font-size:12px;color:#9aa3b0">Seats are limited. Please register at the earliest. This is a personalised link for your use only.</p>'
            . $this->sectionClose();

        return $this->emailWrap($body);
    }

    // ── 4. REGISTRATION RECEIVED ────────────────────────────────
    private function tplRegistrationReceived(string $name, string $regNo, string $designation, string $company): string
    {
        $body = $this->sectionOpen()
            . $this->eyebrow('Registration Received')
            . $this->heading('We have your details &#x2705;')
            . $this->para("Dear <strong style=\"color:#0e1c38\">{$this->e($name)}</strong>,<br><br>Thank you for registering for Corporate World Cup. Your application has been submitted and is currently <strong>pending review</strong> by our team.")
            . $this->infoBox('Event', $this->e($this->eventDateTime) . '<br>' . $this->e($this->eventVenue))
            . $this->infoBox('Registration No.', "<span style=\"font-family:ui-monospace,monospace;font-size:18px\">{$this->e($regNo)}</span>")
            . ($designation || $company ? $this->infoBox('Profile', $this->e($designation) . ($company ? ' &middot; ' . $this->e($company) : '')) : '')
            . $this->infoBox('Status', '<span style="color:#c9930a;font-weight:900">&#x23F3; Pending Approval</span>')
            . '<div style="background:#fffdf8;border:1px solid #ebe4d7;border-radius:14px;padding:14px 20px;margin-top:4px">'
            . '<p style="margin:0;font-size:13px;color:#7c6a46;line-height:1.7">Once your registration is approved, you will receive your <strong>QR event credential</strong> via email. Please keep this email for your reference.</p>'
            . '</div>'
            . $this->sectionClose();

        return $this->emailWrap($body);
    }

    // ── 5. REJECTION ────────────────────────────────────────────
    private function tplRejection(string $name, string $reason): string
    {
        $body = $this->sectionOpen()
            . $this->eyebrow('Registration Update')
            . $this->heading('Thank you for your interest')
            . $this->para("Dear <strong style=\"color:#0e1c38\">{$this->e($name)}</strong>,<br><br>We appreciate your interest in Corporate World Cup and the time you took to register.")
            . '<div style="background:#fff7f7;border:1px solid #f0d2d2;border-radius:14px;padding:16px 20px;margin-bottom:20px">'
            . '<div style="font-size:10px;letter-spacing:1.5px;text-transform:uppercase;color:#a32929;font-weight:800;margin-bottom:6px">Registration Status</div>'
            . '<div style="font-size:14px;color:#7a2020;line-height:1.6">' . $this->e($reason) . '</div>'
            . '</div>'
            . $this->para('We hope to see you at future Corporate World Cup events. For any queries, please reach out to us at <a href="mailto:partners@corporateworldcup.com" style="color:#9e6b20">partners@corporateworldcup.com</a>')
            . $this->sectionClose();

        return $this->emailWrap($body);
    }

    // ── 6. APPROVAL + QR CREDENTIAL ─────────────────────────────
    private function tplApprovalWithQr(string $name, string $regNo, string $designation, string $company, string $category, string $qrToken, string $eventDate, string $venue, array $nominations = []): string
    {
        $credentialUrl = 'https://launch.corporateworldcup.com/event-register/credential.html?token=' . urlencode($qrToken);
        $qrApiUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . urlencode($credentialUrl);
        $nominationHtml = '';
        foreach ($nominations as $nomination) {
            $nomination = (array) $nomination;
            $award = $this->e(trim((string) ($nomination['award_title'] ?? 'PCL Legacy Recognition')));
            $subtitle = $this->e(trim((string) ($nomination['award_subtitle'] ?? '')));
            $by = $this->e(trim((string) ($nomination['nominator_name'] ?? $nomination['nominator_name_snapshot'] ?? '')));
            $reason = $this->e(trim((string) ($nomination['nomination_reason'] ?? '')));
            $nominationHtml .= '<div style="background:#fff9ec;border:1px solid #dfbf79;border-left:4px solid #ad7928;border-radius:14px;padding:17px 19px;margin-bottom:14px;text-align:left">'
                . '<div style="font-size:10px;letter-spacing:1.6px;text-transform:uppercase;color:#8d6924;font-weight:800;margin-bottom:8px">PCL Legacy Recognition &middot; Nominated Player</div>'
                . '<div style="font-family:Georgia,serif;font-size:19px;line-height:1.25;color:#0e1c38;font-weight:700">' . $award . '</div>'
                . ($subtitle !== '' ? '<div style="font-size:12px;line-height:1.5;color:#8d6924;font-weight:700;margin-top:4px">' . $subtitle . '</div>' : '')
                . ($by !== '' ? '<div style="font-size:12px;line-height:1.6;color:#566078;margin-top:11px"><strong style="color:#0e1c38">Nominated by:</strong> ' . $by . '</div>' : '')
                . ($reason !== '' ? '<div style="font-size:12px;line-height:1.6;color:#566078;margin-top:3px"><strong style="color:#0e1c38">Why nominated:</strong> ' . $reason . '</div>' : '')
                . '</div>';
        }

        $body = $this->sectionOpen()
            . $this->eyebrow('Registration Approved')
            . $this->heading('You\'re In! &#x1F389;')
            . $this->para("Dear <strong style=\"color:#0e1c38\">{$this->e($name)}</strong>,<br><br>Congratulations! Your registration for <strong>Corporate World Cup</strong> has been <span style=\"color:#116347;font-weight:800\">approved</span>. Your event credential is ready.")
            . $nominationHtml

            // Guest details block
            . '<table cellpadding="0" cellspacing="0" style="background:#fffdf8;border:1px solid rgba(173,121,40,.25);border-radius:16px;padding:20px;width:100%;margin-bottom:20px">'
            . '<tr><td>'
            . '<div style="font-size:10px;letter-spacing:2px;text-transform:uppercase;color:#8d6924;font-weight:800;margin-bottom:14px">Event Credential</div>'
            . '<table width="100%" cellpadding="0" cellspacing="0">'
            . '<tr><td style="width:60%;vertical-align:top">'
            . "<div style=\"font-size:22px;font-weight:500;color:#0e1c38;font-family:Georgia,serif;margin-bottom:4px\">{$this->e($name)}</div>"
            . "<div style=\"font-size:12px;font-weight:800;color:#7c5b25;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px\">{$this->e($category)}</div>"
            . "<div style=\"font-size:12px;color:#6d778b;margin-bottom:4px\">{$this->e($designation)}" . ($company ? " &middot; {$this->e($company)}" : '') . "</div>"
            . "<div style=\"font-size:11px;color:#9aa3b0\">{$this->e($eventDate)} &middot; {$this->e($venue)}</div>"
            . "<div style=\"margin-top:10px;font-family:ui-monospace,monospace;font-size:13px;font-weight:800;color:#6f7889\">{$this->e($regNo)}</div>"
            . '</td>'
            . "<td style=\"width:40%;text-align:right;vertical-align:middle\">"
            . "<img src=\"{$qrApiUrl}\" width=\"120\" height=\"120\" alt=\"QR Code\" style=\"border-radius:10px;border:1px solid #ebe4d7;display:block;margin-left:auto\">"
            . '</td></tr></table>'
            . '</td></tr></table>'

            . $this->btn($credentialUrl, 'View Full Credential Card &rarr;')

            . '<div style="background:#f0f9f4;border:1px solid #c8e6d4;border-radius:12px;padding:14px 20px;margin-bottom:20px">'
            . '<p style="margin:0;font-size:12px;color:#2d6a4f;line-height:1.7">&#x1F4F1; <strong>At the Event:</strong> Show this email or scan the QR code above at the entry gate. Ensure you are carrying a valid ID.</p>'
            . '</div>'

            . '<table cellpadding="0" cellspacing="0" style="width:100%;margin-top:8px"><tr>'
            . '<td style="width:33%;padding:12px;border-top:1px solid #ede8df;text-align:center"><div style="font-size:10px;color:#8d6924;font-weight:800;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px">Date</div><div style="font-size:13px;font-weight:700;color:#0e1c38">' . $this->e($eventDate) . '</div></td>'
            . '<td style="width:33%;padding:12px;border-top:1px solid #ede8df;text-align:center;border-left:1px solid #ede8df"><div style="font-size:10px;color:#8d6924;font-weight:800;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px">Venue</div><div style="font-size:13px;font-weight:700;color:#0e1c38">' . $this->e($venue) . '</div></td>'
            . '<td style="width:33%;padding:12px;border-top:1px solid #ede8df;text-align:center;border-left:1px solid #ede8df"><div style="font-size:10px;color:#8d6924;font-weight:800;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px">Category</div><div style="font-size:13px;font-weight:700;color:#0e1c38">' . $this->e($category) . '</div></td>'
            . '</tr></table>'
            . $this->sectionClose();

        return $this->emailWrap($body);
    }

    // ── 7. EVENT REMINDER ───────────────────────────────────────
    private function tplReminder(string $name, string $regNo, string $credentialUrl, string $eventDate, string $venue, string $reportingTime): string
    {
        $body = $this->sectionOpen()
            . $this->eyebrow('Event Reminder')
            . $this->heading('See you tomorrow! &#x1F3CF;')
            . $this->para("Dear <strong style=\"color:#0e1c38\">{$this->e($name)}</strong>,<br><br>This is a friendly reminder that <strong>Corporate World Cup</strong> is happening tomorrow. We look forward to welcoming you.")
            . $this->infoBox('Date', $this->e($eventDate))
            . $this->infoBox('Venue', $this->e($venue))
            . ($reportingTime ? $this->infoBox('Reporting Time', $this->e($reportingTime)) : '')
            . $this->infoBox('Your Registration', "<span style=\"font-family:ui-monospace,monospace\">{$this->e($regNo)}</span>")
            . $this->btn($credentialUrl, 'View Your Event Credential &rarr;')
            . '<div style="background:#fffdf8;border:1px solid #ebe4d7;border-radius:12px;padding:14px 20px">'
            . '<p style="margin:0;font-size:12px;color:#7c6a46;line-height:1.7">Please carry a <strong>valid government ID</strong> along with your QR credential at the venue entry.</p>'
            . '</div>'
            . $this->sectionClose();

        return $this->emailWrap($body);
    }
}
