<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
header("Content-Type: application/json");

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../vendor/autoload.php';

include('config.php');

date_default_timezone_set("Asia/Kolkata");

$requestData = json_decode(file_get_contents("php://input"), true);
if (!is_array($requestData)) { $requestData = []; }

error_log("sponserEmailTemplate.php received requestData: " . json_encode($requestData));

/* ══════════════════════════════════════════════════════════════════
   ENTERPRISE EMAIL TRACKING (pclTeamRegister style — EmailTrackingApiClient)
   ══════════════════════════════════════════════════════════════════ */

/* ── PCL ERROR LOG HELPER ── */
if (!function_exists('pcl_write_error_log')) {
    function pcl_write_error_log($context, $data = []) {
        $logDir = __DIR__ . '/logs';
        if (!is_dir($logDir)) {
            @mkdir($logDir, 0755, true);
        }
        $logFile = $logDir . '/email_log_' . date('Y-m-d') . '.log';
        $entry = [
            'time'    => date('Y-m-d H:i:s'),
            'context' => $context,
            'data'    => $data,
        ];
        $line = json_encode($entry, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n---\n";
        @file_put_contents($logFile, $line, FILE_APPEND | LOCK_EX);
    }
}

/* ── ENTERPRISE EMAIL LOGGING CLIENT ── */
$__pclEmailTrackingClient = __DIR__ . '/EmailTrackingApiClient.php';
if (file_exists($__pclEmailTrackingClient)) {
    require_once $__pclEmailTrackingClient;
}

if (!function_exists('pcl_email_runtime_url')) {
    function pcl_email_runtime_url()
    {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host   = $_SERVER['HTTP_HOST'] ?? 'wplspeedqueen.com';
        $uri    = $_SERVER['REQUEST_URI'] ?? ($_SERVER['SCRIPT_NAME'] ?? '');
        return $scheme . '://' . $host . $uri;
    }
}

if (!function_exists('pcl_email_public_file_url')) {
    function pcl_email_public_file_url()
    {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host   = $_SERVER['HTTP_HOST'] ?? 'wplspeedqueen.com';
        $script = $_SERVER['SCRIPT_NAME'] ?? '';
        return $script ? ($scheme . '://' . $host . $script) : null;
    }
}

if (!function_exists('pcl_email_flatten_text')) {
    function pcl_email_flatten_text($html)
    {
        return trim(preg_replace('/\s+/', ' ', html_entity_decode(strip_tags((string)$html), ENT_QUOTES, 'UTF-8')));
    }
}

if (!function_exists('pcl_email_normalize_attachment_urls')) {
    function pcl_email_normalize_attachment_urls($attachments)
    {
        if (empty($attachments)) return [];
        if (is_string($attachments)) {
            $decoded = json_decode($attachments, true);
            if (is_array($decoded)) $attachments = $decoded;
            else $attachments = array_filter(array_map('trim', explode(',', $attachments)));
        }
        $urls = [];
        if (is_array($attachments)) {
            foreach ($attachments as $item) {
                if (is_string($item) && $item !== '') {
                    $urls[] = $item;
                } elseif (is_array($item)) {
                    $url = $item['url'] ?? $item['attachment_url'] ?? $item['file_url'] ?? $item['href'] ?? null;
                    if (!empty($url)) $urls[] = $url;
                }
            }
        }
        return array_values(array_unique(array_filter($urls)));
    }
}

if (!function_exists('pcl_email_enterprise_track')) {
    function pcl_email_enterprise_track($mail = null, $status = 'sent', array $extra = array()) {
        try {
            $to = array();
            if (is_object($mail) && method_exists($mail, 'getToAddresses')) {
                $to = $mail->getToAddresses();
            }
            $firstTo = isset($to[0]) ? $to[0] : array('', '');
            $recipientEmail = $extra['recipient_email'] ?? ($firstTo[0] ?? '');
            $recipientName  = $extra['recipient_name']  ?? ($firstTo[1] ?? '');

            $subject = is_object($mail) && isset($mail->Subject) ? $mail->Subject : ($extra['subject'] ?? '');
            $body    = is_object($mail) && isset($mail->Body) ? $mail->Body : ($extra['full_email_html'] ?? '');

            $payload = array_merge(array(
                'recipient_email'   => $recipientEmail,
                'recipient_name'    => $recipientName,
                'subject'           => $subject,
                'full_email_html'   => $body,
                'status'            => $status,
                'delivery_status'   => $status,
                'error_message'     => $extra['error_message'] ?? null,
                'active_file_name'  => basename(__FILE__),
                'request_uri'       => $_SERVER['REQUEST_URI'] ?? '',
            ), $extra);

            if (class_exists('EmailTrackingApiClient') && method_exists('EmailTrackingApiClient', 'trackLegacy')) {
                return EmailTrackingApiClient::trackLegacy($payload);
            }

            return array('tracking_status' => 'skipped', 'reason' => 'EmailTrackingApiClient class not found');
        } catch (Throwable $e) {
            return array('tracking_status' => 'failed', 'error' => $e->getMessage());
        }
    }
}

if (!function_exists('pcl_email_log_dynamic')) {
    function pcl_email_log_dynamic($mail, $emailBody, array $postData = [], array $extra = [])
    {
        if (!class_exists('EmailTrackingApiClient')) {
            return ['tracking_status' => 'skipped', 'reason' => 'EmailTrackingApiClient not found'];
        }

        $status = $extra['status'] ?? 'sent';
        $deliveryStatus = $extra['delivery_status'] ?? $status;

        $attachmentUrls = pcl_email_normalize_attachment_urls(
            $extra['attachment_urls'] ?? $postData['attachment_urls'] ?? $postData['attachments'] ?? []
        );

        $requestPayload = [];
        if (isset($GLOBALS['requestData']) && is_array($GLOBALS['requestData'])) $requestPayload = $GLOBALS['requestData'];
        elseif (isset($GLOBALS['data']) && is_array($GLOBALS['data'])) $requestPayload = $GLOBALS['data'];
        else $requestPayload = $postData;

        $subject = '';
        if (is_object($mail) && isset($mail->Subject)) $subject = (string)$mail->Subject;
        if ($subject === '') $subject = (string)($postData['subject'] ?? $extra['subject'] ?? '');

        $recipientEmail = $extra['recipient_email'] ?? $postData['email'] ?? $postData['recipient_email'] ?? $GLOBALS['email'] ?? '';
        $recipientName  = $extra['recipient_name']  ?? $postData['name'] ?? $postData['person_name'] ?? $postData['full_name'] ?? $GLOBALS['toName'] ?? '';
        $recipientMobile = $extra['recipient_mobile'] ?? $postData['mobile'] ?? $postData['phone'] ?? $postData['recipient_mobile'] ?? '';
        $leadId = $extra['lead_id'] ?? $postData['lead_id'] ?? $postData['reference_id'] ?? $GLOBALS['leadId'] ?? '';

        $messageId = null;
        if (is_object($mail) && method_exists($mail, 'getLastMessageID')) {
            $messageId = $mail->getLastMessageID();
        }

        $html = (string)($emailBody ?: (is_object($mail) && isset($mail->Body) ? $mail->Body : ''));

        $payload = [
            'lead_id'            => $leadId,
            'team_id'            => $extra['team_id'] ?? $postData['team_id'] ?? $postData['teamId'] ?? '',
            'user_id'            => $extra['user_id'] ?? $postData['user_id'] ?? $postData['userId'] ?? '',

            'recipient_email'    => $recipientEmail,
            'recipient_name'     => $recipientName,
            'recipient_mobile'   => $recipientMobile,
            'email'              => $recipientEmail,
            'mobile'             => $recipientMobile,

            'subject'            => $subject,
            'preheader'          => $extra['preheader'] ?? $postData['preheader'] ?? '',

            'full_email_html'    => $html,
            'full_email_text'    => pcl_email_flatten_text($html),

            'attachment_urls'    => implode(',', $attachmentUrls),
            'attachments_json'   => json_encode($attachmentUrls, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'attachment_count'   => count($attachmentUrls),

            'current_email_url'  => pcl_email_runtime_url(),
            'public_calling_url' => pcl_email_runtime_url(),
            'calling_file_url'   => $extra['calling_file_url'] ?? $postData['calling_file_url'] ?? $requestPayload['calling_file_url'] ?? ($_SERVER['HTTP_REFERER'] ?? null),
            'calling_page_url'   => $extra['calling_page_url'] ?? $postData['calling_page_url'] ?? $requestPayload['calling_page_url'] ?? ($_SERVER['HTTP_REFERER'] ?? null),
            'direct_email_url'   => pcl_email_public_file_url(),
            'server_full_path'   => __FILE__,
            'server_file_path'   => __FILE__,
            'script_name'        => basename(__FILE__),
            'active_file_name'   => basename(__FILE__),
            'request_uri'        => $_SERVER['REQUEST_URI'] ?? null,

            'status'             => $status,
            'delivery_status'    => $deliveryStatus,
            'provider_message_id'=> $messageId,
            'error_message'      => $extra['error_message'] ?? null,

            'request_payload_json' => $requestPayload,
            'response_json'        => $extra['response_json'] ?? [
                'status' => $status,
                'message' => $extra['message'] ?? null,
                'provider_message_id' => $messageId,
            ],
        ];

        try {
            return EmailTrackingApiClient::trackLegacy($payload);
        } catch (Throwable $trackingException) {
            return [
                'tracking_status' => 'failed',
                'error' => $trackingException->getMessage(),
            ];
        }
    }
}

if (!function_exists('pcl_track_email_if_available')) {
    function pcl_track_email_if_available($mail, $extra = []) {
        try {
            if (function_exists('pcl_email_enterprise_track_send')) {
                return pcl_email_enterprise_track_send($mail, $extra);
            }
            if (class_exists('EmailTrackingApiClient') && method_exists('EmailTrackingApiClient', 'trackLegacy')) {
                $payload = array_merge([
                    'active_file_name' => basename(__FILE__),
                    'lead_id'          => $extra['lead_id'] ?? null,
                    'recipient_email'  => $extra['recipient_email'] ?? '',
                    'recipient_name'   => $extra['recipient_name'] ?? '',
                    'subject'          => is_object($mail) ? ($mail->Subject ?? '') : '',
                    'status'           => 'sent',
                    'source'           => 'sponsor_brand_email_template',
                ], $extra);
                return EmailTrackingApiClient::trackLegacy($payload);
            }
        } catch (Throwable $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
        return ['success' => false, 'message' => 'Tracking client not available'];
    }
}

/* Still needed to build a "calling file url" fallback for tracking payloads */
function pclBuildCallingFileUrl(array $requestData)
{
    foreach ([
        'calling_file_url',
        'calling_page_url',
        'parent_page_url',
        'source_url',
        'admin_page_url',
        'source_page_url',
        'referrer_url',
        'referer_url'
    ] as $key) {
        if (!empty($requestData[$key])) {
            return $requestData[$key];
        }
    }

    if (!empty($_SERVER['HTTP_REFERER'])) {
        return $_SERVER['HTTP_REFERER'];
    }

    $brandName = $requestData['brand_name'] ?? '';
    $query = http_build_query([
        'brand_name' => $brandName
    ]);

    return 'https://procorporateleague.com/2026/admin/pcl-lead-management/sponsor-email.php' . ($query ? '?' . $query : '');
}

function pclPublicUrlForSameFolder($fileName)
{
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? 'wplspeedqueen.com';
    $script = $_SERVER['SCRIPT_NAME'] ?? '/email_api/sponserEmailTemplate.php';
    $dir    = rtrim(str_replace('\\', '/', dirname($script)), '/');
    return $scheme . '://' . $host . $dir . '/' . ltrim($fileName, '/');
}
/* ── END TRACKING HELPERS ── */

$email  = trim((string)($requestData['email'] ?? $requestData['to_email'] ?? ''));
$toName = trim((string)($requestData['to_name'] ?? ''));
$leadId = $requestData['lead_id'] ?? null;

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(["status_code" => 400, "status" => "error", "message" => "A valid recipient email is required"]);
    exit;
}

// ===============================
// FIX: cc_list ko null vs empty-array ke roop mein differentiate karo.
// - key hi nahi bheji gayi (null)  -> legacy/direct caller, purana hardcoded
//   internal-team CC fallback lagega (backward compatible).
// - empty array [] jaanbujh kar bheji gayi -> koi CC add nahi hoga
//   (yeh multi-recipient loop ke case mein use hota hai, taaki
//   duplicate recipients ke saath CC baar-baar na jaye).
// - non-empty array -> wahi CC add honge jo bheje gaye hain.
// ===============================
$ccList = $requestData['cc_list'] ?? null;

// ===============================
// MULTIPLE ATTACHMENTS — cc_list jaisa pattern
// - $requestData['attachments'] = [ ['url' => '...', 'name' => '...'], ... ]
//   -> jitne bheje jayenge, utne hi attach honge (naya multi-attachment tarika)
// - Backward compat: agar purana single attachment_url / attachment_name
//   bheja gaya hai (attachments key ke bina), toh woh bhi ek attachment
//   ki tarah list mein add ho jayega — purana caller tootega nahi.
// - Default static roadmap PDF hamesha attach hoga, iska in dono se
//   koi lena dena nahi (neeche PDF ATTACHMENTS section mein as-is hai).
// ===============================
$rawAttachments = $requestData['attachments'] ?? null;

$attachmentList = []; // normalized: [ ['url' => ..., 'name' => ...], ... ]

if (is_array($rawAttachments) && count($rawAttachments) > 0) {
    foreach ($rawAttachments as $att) {
        if (!is_array($att)) { continue; }
        $attUrl  = trim((string)($att['url'] ?? $att['attachment_url'] ?? $att['file_url'] ?? ''));
        $attName = trim((string)($att['name'] ?? $att['attachment_name'] ?? $att['file_name'] ?? ''));
        $attData = trim((string)($att['data_base64'] ?? $att['content_base64'] ?? ''));
        $attMime = trim((string)($att['mime_type'] ?? $att['type'] ?? 'application/octet-stream'));

        if ($attName === '') { continue; }
        if ($attUrl === '' && $attData === '') { continue; }

        $attachmentList[] = [
            'url'         => $attUrl,
            'name'        => $attName,
            'data_base64' => $attData,
            'mime_type'   => $attMime !== '' ? $attMime : 'application/octet-stream',
        ];
    }
}

// Backward compat: legacy single attachment_url / attachment_name (sirf tab
// use hoga jab naya 'attachments' array bheja hi na gaya ho)
$legacyAttachmentUrl  = trim((string)($requestData['attachment_url'] ?? ''));
$legacyAttachmentName = trim((string)($requestData['attachment_name'] ?? ''));

if ($rawAttachments === null && $legacyAttachmentUrl !== '' && $legacyAttachmentName !== '') {
    $attachmentList[] = [
        'url' => $legacyAttachmentUrl,
        'name' => $legacyAttachmentName,
        'data_base64' => '',
        'mime_type' => 'application/octet-stream',
    ];
}

// template_id — agar request mein nahi mila ya invalid hai,
// toh hardcoded 6 nahi, email_template table ka LAST INSERTED ID lo.
$templateId = isset($requestData['template_id']) ? (int)$requestData['template_id'] : 0;

if ($templateId <= 0) {
    $lastIdSql = "SELECT id FROM `email_template` ORDER BY id DESC LIMIT 1";
    $lastIdRes = mysqli_query($conn, $lastIdSql);
    $lastIdRow = $lastIdRes ? mysqli_fetch_assoc($lastIdRes) : null;
    $templateId = $lastIdRow ? (int)$lastIdRow['id'] : 6; // final safety fallback
}

/* ===============================
   SMTP CREDENTIALS
================================ */
$smtpSql = "SELECT * FROM `smtp_auth_data` WHERE id = 1";
$smtpExe = mysqli_query($conn, $smtpSql);
$smtpRow = $smtpExe ? mysqli_fetch_assoc($smtpExe) : null;

if (empty($smtpRow)) {
    pcl_write_error_log('smtp_missing', ['lead_id' => $leadId]);
    echo json_encode(["status_code" => 400, "status" => "error", "message" => "SMTP AUTH MISSING"]);
    exit;
}

/* ===============================
   SPONSOR BRAND EMAIL TEMPLATE
   Corporate World Cup Partnership Opportunity
================================ */

$brandName       = trim((string)($requestData['brand_name'] ?? 'SKORE'));
$partnerTitle    = trim((string)($requestData['partner_title'] ?? 'Official Confidence Partner Opportunity'));
$brandLine       = trim((string)($requestData['brand_line'] ?? 'Confidence Before Performance'));
$brandWebsite    = trim((string)($requestData['brand_website'] ?? 'https://www.skorecondoms.com/'));
$meetingUrl      = trim((string)($requestData['meeting_url'] ?? 'mailto:sachin.gupta@procorporateleague.com?subject=SKORE%20x%20Corporate%20World%20Cup%20Partnership%20Discussion'));
$cwcUrl          = 'https://corporateworldcup.com/';
$pclUrl          = 'https://www.procorporateleague.com/';
$roadUrl         = 'https://www.roadtocorporateworldcup.com/';

$safeBrand       = htmlspecialchars($brandName, ENT_QUOTES, 'UTF-8');
$safePartner     = htmlspecialchars($partnerTitle, ENT_QUOTES, 'UTF-8');
$safeBrandLine   = htmlspecialchars($brandLine, ENT_QUOTES, 'UTF-8');
$safeToName      = htmlspecialchars($toName, ENT_QUOTES, 'UTF-8');

// Logo handling — uploaded logo priority, warna block hide
$uploadedLogoUrl = trim((string)($requestData['logo_url'] ?? ''));
$hasLogo         = !empty($uploadedLogoUrl);
$brandLogo       = $hasLogo ? $uploadedLogoUrl : '';
$logoBlockDisplay = $hasLogo ? '' : 'display:none;';

$trophyImage     = 'https://wplspeedqueen.com/email_api/cwctrophy.png';
$firechatImage   = 'https://wplspeedqueen.com/email_api/firechat.png';
$pclLogo         = 'https://www.procorporateleague.com/2026/pcl/Imp_PCL_Logo_Black.png';
$sonyLivLogo     = 'https://www.procorporateleague.com/2026/pcl/SonyLIV_2020.png';
$cwcHeroImage    = 'https://www.roadtocorporateworldcup.com/assets/corporateworldcup.jpeg';
$celebrityImage  = 'https://www.roadtocorporateworldcup.com/assets/PCLxCelebrity_Engagement.jpeg';
$chrisGayleImage = 'https://www.procorporateleague.com/uploads/sliders/mobile/images/20260603085928_Chris_Gayle_X_PCL__Slider_for_Mobile_.jpg';
$championsVideo  = 'https://procorporateleague.com/assets/highlights/2025_Corporate_Champions.mp4';
$sonyLivCoverageUrl = 'https://www.procorporateleague.com/pcl/media/pcl-eleven11-sony-liv-highlight/';

$cities = [
    'Delhi NCR','Noida','Gurugram','Ghaziabad','Mumbai','Pune','Bengaluru','Hyderabad',
    'Chennai','Kolkata','Ahmedabad','Jaipur','Lucknow','Chandigarh','Indore','Bhopal',
    'Nagpur','Surat','Vadodara','Kochi','Coimbatore','Bhubaneswar','Patna','Dehradun'
];

/* ---- Build the 24-city cards grid ---- */
$cityCardsRows = '';
for ($i = 0; $i < count($cities); $i += 4) {
    $cityCardsRows .= "          <tr>\n";
    for ($j = 0; $j < 4; $j++) {
        $city = $cities[$i + $j] ?? '';
        if ($city === '') { continue; }
        $safeCity = htmlspecialchars($city, ENT_QUOTES, 'UTF-8');
        $cityCardsRows .= <<<HTML
            <td width="25%" style="padding:6px;">
              <div style="background:#ffffff;border:1px solid #ead69d;border-radius:14px;padding:13px 9px;text-align:center;min-height:58px;">
                <div style="font-size:14px;font-weight:bold;color:#071d46;line-height:1.3;">{$safeCity}</div>
                <div style="font-size:10px;color:#7b6a37;line-height:1.5;margin-top:5px;">Confidence Story</div>
              </div>
            </td>
HTML;
        $cityCardsRows .= "\n";
    }
    $cityCardsRows .= "          </tr>\n";
}

/* ---- Exact Builder HTML has priority. Database is legacy fallback only. ---- */
$templateIdSafe = (int)$templateId;
$emailBody = '';
$templateSource = '';

foreach (['html_body', 'template_html', 'template_file'] as $htmlKey) {
    if (!empty($requestData[$htmlKey]) && is_string($requestData[$htmlKey])) {
        $emailBody = $requestData[$htmlKey];
        $templateSource = 'request_html';
        break;
    }
}

if ($emailBody !== '' && !empty($requestData['html_sha256'])) {
    $actualHash = hash('sha256', $emailBody);

    if (!hash_equals((string)$requestData['html_sha256'], $actualHash)) {
        echo json_encode([
            'status_code' => 400,
            'status' => 'error',
            'message' => 'Email HTML integrity validation failed.'
        ]);
        exit;
    }
}

if ($emailBody === '') {
    $sqlTemp = "SELECT * FROM `email_template` WHERE id = {$templateIdSafe}";
    $sqlExe  = mysqli_query($conn, $sqlTemp);
    $sqlRow  = $sqlExe ? mysqli_fetch_assoc($sqlExe) : null;

    if (empty($sqlRow) || empty($sqlRow['template_file'])) {
        echo json_encode([
            'status_code' => 400,
            'status' => 'error',
            'message' => "Email template not found for template_id={$templateIdSafe}"
        ]);
        exit;
    }

    $emailBody = $sqlRow['template_file'];
    $templateSource = 'database_fallback';
}

/* ---- Replace all {{placeholders}} with real dynamic values ---- */
$placeholders = [
    '{{brand_name}}'            => $safeBrand,
    '{{partner_title}}'         => $safePartner,
    '{{brand_line}}'            => $safeBrandLine,
    '{{to_name}}'                => $safeToName,
    '{{cwc_url}}'                 => $cwcUrl,
    '{{pcl_url}}'                 => $pclUrl,
    '{{meeting_url}}'             => $meetingUrl,
    '{{brand_logo}}'              => $brandLogo,
    '{{logo_display}}'            => $logoBlockDisplay,
    '{{trophy_image}}'            => $trophyImage,
    '{{firechat_image}}'          => $firechatImage,
    '{{sony_liv_logo}}'           => $sonyLivLogo,
    '{{cwc_hero_image}}'          => $cwcHeroImage,
    '{{celebrity_image}}'         => $celebrityImage,
    '{{chris_gayle_image}}'       => $chrisGayleImage,
    '{{champions_video}}'         => $championsVideo,
    '{{sony_liv_coverage_url}}'   => $sonyLivCoverageUrl,
    '{{city_cards_rows}}'         => $cityCardsRows,
    '{{category_name}}'           => htmlspecialchars(
        (string)($requestData['category_name'] ?? ''),
        ENT_QUOTES | ENT_HTML5,
        'UTF-8'
    ),
    '{{opportunity_title}}'       => htmlspecialchars(
        (string)($requestData['opportunity_title'] ?? ''),
        ENT_QUOTES | ENT_HTML5,
        'UTF-8'
    ),
    '{{confidence_partner}}'      => htmlspecialchars(
        (string)($requestData['confidence_partner'] ?? ''),
        ENT_QUOTES | ENT_HTML5,
        'UTF-8'
    ),
];

$emailBody = strtr($emailBody, $placeholders);

$dynamicLiteralPairs = [
    [
        (string)($requestData['orig_category_name'] ?? ''),
        (string)($requestData['category_name'] ?? '')
    ],
    [
        (string)($requestData['orig_opportunity_title'] ?? ''),
        (string)($requestData['opportunity_title'] ?? '')
    ],
    [
        (string)($requestData['orig_confidence_partner'] ?? ''),
        (string)($requestData['confidence_partner'] ?? '')
    ],
];

foreach ($dynamicLiteralPairs as [$oldValue, $newValue]) {
    $oldValue = trim($oldValue);
    $newValue = trim($newValue);

    if (
        $oldValue === '' ||
        $newValue === '' ||
        strcasecmp($oldValue, $newValue) === 0
    ) {
        continue;
    }

    $variants = array_unique([
        $oldValue,
        htmlspecialchars(
            $oldValue,
            ENT_QUOTES | ENT_HTML5,
            'UTF-8'
        ),
        html_entity_decode(
            $oldValue,
            ENT_QUOTES | ENT_HTML5,
            'UTF-8'
        ),
    ]);

    foreach ($variants as $variant) {
        if ($variant === '') {
            continue;
        }

        $emailBody = preg_replace(
            '/' . preg_quote($variant, '/') . '/iu',
            htmlspecialchars(
                $newValue,
                ENT_QUOTES | ENT_HTML5,
                'UTF-8'
            ),
            $emailBody
        ) ?? $emailBody;
    }
}

/* ===============================
   FIX: Attachment fetch via cURL (redirect-follow + logging)
   Purana file_get_contents() by default redirect follow NAHI karta,
   aur error silently @ se suppress ho raha tha — isliye attachment
   fail hone ka reason kabhi pata hi nahi chalta tha.

   Ab yeh multiple attachments ke liye loop mein chalta hai —
   $attachmentList mein jitne bhi {url, name} pairs hain, sab fetch
   honge. Har ek ka fetch result (content ya error) $fetchedAttachments
   mein store hota hai taaki attach + tracking + response, sabme use ho.
================================ */
$fetchedAttachments    = [];
$attachmentFetchErrors = [];

foreach ($attachmentList as $attItem) {
    $attUrl    = trim((string)($attItem['url'] ?? ''));
    $attName   = trim((string)($attItem['name'] ?? 'attachment'));
    $attBase64 = trim((string)($attItem['data_base64'] ?? ''));
    $attMime   = trim((string)($attItem['mime_type'] ?? 'application/octet-stream'));

    $attContent = null;
    $fetchErr   = '';
    $source     = '';

    // Preferred path: actual file bytes sent by update_template_new.php.
    // This is reliable even when the uploaded URL is blocked, private,
    // redirected, protected by Cloudflare, or generated with a wrong base URL.
    if ($attBase64 !== '') {
        $decoded = base64_decode($attBase64, true);

        if ($decoded !== false && $decoded !== '') {
            $attContent = $decoded;
            $source = 'base64_payload';
            error_log(
                "Attachment payload OK [{$attName}] (" .
                strlen($attContent) .
                " bytes)"
            );
        } else {
            $fetchErr = "Invalid base64 attachment payload";
        }
    }

    // Backward-compatible fallback for older callers that only send a URL.
    if ($attContent === null && $attUrl !== '') {
        $attCurl = curl_init();

        curl_setopt_array($attCurl, [
            CURLOPT_URL => $attUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_TIMEOUT => 45,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (PCL Email Attachment Fetcher)',
            CURLOPT_HTTPHEADER => [
                'Accept: application/pdf,application/octet-stream,*/*',
            ],
        ]);

        $downloaded   = curl_exec($attCurl);
        $attHttpCode  = (int) curl_getinfo($attCurl, CURLINFO_HTTP_CODE);
        $attCurlError = curl_error($attCurl);
        curl_close($attCurl);

        if (
            $downloaded !== false &&
            $downloaded !== '' &&
            $attCurlError === '' &&
            $attHttpCode >= 200 &&
            $attHttpCode < 400
        ) {
            $attContent = $downloaded;
            $source = 'remote_url';

            error_log(
                "Attachment fetch OK [{$attName}]: {$attUrl} (" .
                strlen($attContent) .
                " bytes)"
            );
        } else {
            $urlError =
                "HTTP {$attHttpCode} | curlError: {$attCurlError} | URL: {$attUrl}";

            $fetchErr = $fetchErr !== ''
                ? $fetchErr . ' | ' . $urlError
                : $urlError;
        }
    }

    if ($attContent === null) {
        error_log("Attachment preparation FAILED [{$attName}]: {$fetchErr}");
        $attachmentFetchErrors[] = "{$attName}: {$fetchErr}";
    }

    $fetchedAttachments[] = [
        'name'      => $attName,
        'url'       => $attUrl,
        'content'   => $attContent,
        'mime_type' => $attMime !== '' ? $attMime : 'application/octet-stream',
        'source'    => $source,
        'error'     => $fetchErr,
    ];
}

$attachmentFetchError = implode(' | ', $attachmentFetchErrors); // backward-compat single string for response/debug

/* ===============================
   SEND EMAIL
================================ */
$mail = new PHPMailer(true);

/* Tracking ke liye pehle se collect kar lo, taaki catch block me bhi mil jaye */
$emailAttachments = [];
$attachmentUrls   = [];
$attachmentCount  = 0;

try {
    $mail->isSMTP();
    $mail->Host       = $smtpRow['smtp_host'];
    $mail->SMTPAuth   = true;
    $mail->Username   = $smtpRow['smtp_username'];
    $mail->Password   = $smtpRow['smtp_password'];
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    $mail->Timeout        = 15;
    $mail->SMTPKeepAlive  = false;
    $mail->SMTPDebug      = 0;
    $mail->Debugoutput    = function($str, $level) {
        error_log("PHPMailer Debug: $str");
    };

    $mail->CharSet  = 'UTF-8';
    $mail->Encoding = 'base64';

    $mail->setFrom('sachin.gupta@procorporateleague.com', 'Pro Corporate League');
    $mail->addAddress($email, $safeToName);

    // ===============================
    // FIX: cc_list null vs [] vs non-empty array ko alag treat karo.
    // ===============================
    if (is_array($ccList) && count($ccList) > 0) {
        // Non-empty CC list bheji gayi -> yehi CC add karo
        foreach ($ccList as $cc) {
            $ccEmail = trim((string)($cc['email'] ?? ''));
            $ccName  = trim((string)($cc['name']  ?? ''));
            if (!empty($ccEmail) && filter_var($ccEmail, FILTER_VALIDATE_EMAIL)) {
                $mail->addCC($ccEmail, $ccName);
            }
        }
    } elseif ($ccList === null) {
        // cc_list key hi request mein nahi thi (legacy/direct call) -> default internal team CC
        $mail->addCC('sachin.gupta@procorporateleague.com', 'Sachin Gupta');
        $mail->addCC('prashish.rana@procorporateleague.com', 'Prashish Rana');
        $mail->addCC('manya.jain@procorporateleague.com', 'Manya Jain');
        $mail->addCC('sachin.gupta@corporateworldcup.com', 'Sachin Gupta');
    }
    // agar $ccList === [] (jaanbujh kar empty bheja gaya), koi CC add nahi hoga

    $mail->isHTML(true);

    /* ── PDF ATTACHMENTS (existing static roadmap file — DEFAULT, hamesha attach hoga) ── */
    $pdf2Path = __DIR__ . '/CorporateWorldCup_X_Roadmap_2026-27.pdf';

    if (file_exists($pdf2Path)) {
        $mail->addAttachment($pdf2Path, 'PCL_CorporateWorldCup_X_Roadmap_2026-27.pdf');

        $pdf2Url = pclPublicUrlForSameFolder(basename($pdf2Path));
        $emailAttachments[] = [
            'file_name'   => 'PCL_CorporateWorldCup_X_Roadmap_2026-27.pdf',
            'url'         => $pdf2Url,
            'server_path' => $pdf2Path,
            'mime_type'   => 'application/pdf',
            'type'        => 'pdf',
            'size_bytes'  => filesize($pdf2Path),
            'disposition' => 'attachment'
        ];
        $attachmentUrls[]  = $pdf2Url;
        $attachmentCount++;
    } else {
        error_log("Static PDF attachment not found at: {$pdf2Path}");
    }
    /* ── END PDF ATTACHMENTS ── */

    /* ── USER-UPLOADED ATTACHMENTS (multiple, cc_list jaisa pattern) ── */
    $uploadedAttachedCount = 0;
    $uploadedFailedNames   = [];

    foreach ($fetchedAttachments as $fa) {
        if ($fa['content'] !== null) {
            $mail->addStringAttachment(
                $fa['content'],
                $fa['name'],
                PHPMailer::ENCODING_BASE64,
                $fa['mime_type'] ?? 'application/octet-stream'
            );

            $emailAttachments[] = [
                'file_name'   => $fa['name'],
                'url'         => $fa['url'],
                'server_path' => '',
                'mime_type'   => $fa['mime_type'] ?? 'application/octet-stream',
                'type'        => 'uploaded',
                'source'      => $fa['source'] ?? '',
                'size_bytes'  => strlen($fa['content']),
                'disposition' => 'attachment'
            ];
            $attachmentUrls[] = $fa['url'];
            $attachmentCount++;
            $uploadedAttachedCount++;
        } else {
            $uploadedFailedNames[] = $fa['name'];
        }
    }
    /* ── END USER-UPLOADED ATTACHMENTS ── */

    $requestedSubject = trim((string)($requestData['subject'] ?? ''));

    $requestedSubject = trim((string)preg_replace(
        '/[\r\n]+/',
        ' ',
        $requestedSubject
    ));

    if ($requestedSubject === '') {
        $subjectBrand = trim((string)(
            $requestData['brand_name'] ?? $brandName ?? ''
        ));

        if ($subjectBrand === '') {
            $subjectBrand = 'Your Brand';
        }

        $requestedSubject =
            $subjectBrand .
            ' × PCL: FMCG Visibility and Consumer Engagement Proposal';
    }

    $mail->Subject = $requestedSubject;
    $mail->Body    = $emailBody;
    $mail->AltBody = 'Please view this email in an HTML-compatible email client.';

    /* ── ACTUAL SEND ── */
    $mail->send();

    $providerMessageId = method_exists($mail, 'getLastMessageID') ? $mail->getLastMessageID() : '';

    $attachmentStatusMsg = $uploadedAttachedCount . ' uploaded attachment(s) attached successfully';
    if (!empty($uploadedFailedNames)) {
        $attachmentStatusMsg .= '; FAILED: ' . implode(', ', $uploadedFailedNames);
    }
    if (empty($attachmentList)) {
        $attachmentStatusMsg = 'no uploaded attachment provided';
    }

    $successPayload = [
        "status_code" => 200,
        "status"      => "success",
        "message"     => "Sponsor brand email sent successfully",
        "template_id" => $templateIdSafe,
        "logo_used"   => $hasLogo ? $brandLogo : "no logo uploaded — block hidden",
        "attachment_status" => $attachmentStatusMsg,
        "attachment_count"  => $attachmentCount,
        "uploaded_attachment_count" => $uploadedAttachedCount,
        "attachment_fetch_errors" => $attachmentFetchErrors
    ];

    /* ─────────────────────────────────────────────
       CRITICAL FIX FOR 504 TIMEOUT:
       Response pehle client ko bhejo, uske baad tracking API call karo,
       taaki client turant response pa jaye aur tracking background me chale.
    ───────────────────────────────────────────── */
    echo json_encode($successPayload);

    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    } else {
        if (ob_get_level() > 0) {
            @ob_end_flush();
        }
        flush();
    }

    /* ── ENTERPRISE TRACKING CALL (background, non-blocking for client) ── */
    $callingFileUrl = pclBuildCallingFileUrl($requestData);

    $postDataForTracking = [
        'email'            => $email,
        'name'             => $toName,
        'lead_id'          => $requestData['lead_id'] ?? null,
        'reference_id'     => $requestData['lead_id'] ?? '',
        'user_id'          => $requestData['user_id'] ?? null,
        'mobile'           => $requestData['mobile'] ?? '',
        'calling_file_url' => $callingFileUrl,
        'calling_page_url' => $callingFileUrl,
        'attachment_urls'  => $attachmentUrls,
    ];

    // ✅ module_id / submodule_id hardcode kiya — backend 'module_id cannot be null' error fix
    $enterpriseTrackResult = pcl_email_enterprise_track($mail, 'sent', [
        'recipient_email' => $email,
        'recipient_name'  => $toName,
        'lead_id'         => $requestData['lead_id'] ?? null,
        'module_id'       => 10,
        'submodule_id'    => 10,
        'module_key'      => 'sponsor',
        'submodule_key'   => 'sponsor',
        'journey_entity_type' => 'sponsor_brand',
        'journey_entity_id'   => $brandName,
    ]);

    $trackingResult = pcl_email_log_dynamic($mail, $emailBody, $postDataForTracking, [
        'status'            => 'sent',
        'delivery_status'   => 'sent',
        'message'           => 'Sponsor brand email sent successfully',
        'lead_id'           => $requestData['lead_id'] ?? null,
        'attachment_urls'   => $attachmentUrls,
        'calling_file_url'  => $callingFileUrl,
        'calling_page_url'  => $callingFileUrl,
        'module_id'         => 10,
        'submodule_id'      => 10,
        'module_key'        => 'sponsor',
        'submodule_key'     => 'sponsor',
    ]);

    pcl_write_error_log('email_sent_success', [
        'to'                  => $email,
        'lead_id'             => $requestData['lead_id'] ?? null,
        'attachment_count'    => $attachmentCount,
        'tracking'            => $trackingResult,
        'enterprise_tracking' => $enterpriseTrackResult,
    ]);

} catch (Exception $e) {
    error_log("PHPMailer send() failed: " . $mail->ErrorInfo);

    $errorMessage = $mail->ErrorInfo ?: $e->getMessage();
    $failedSubject = !empty($mail->Subject)
        ? $mail->Subject
        : ($safeBrand . ' x Corporate World Cup | Official Confidence Partner Opportunity');

    echo json_encode([
        "status_code" => 500,
        "status"      => "error",
        "message"     => $errorMessage,
        "debug"       => [
            "email"       => $email,
            "toName"      => $toName,
            "brandName"   => $brandName,
            "template_id" => $templateIdSafe,
            "smtp_host"   => $smtpRow['smtp_host'] ?? '',
            "smtp_user"   => $smtpRow['smtp_username'] ?? '',
            "attachment_fetch_error" => $attachmentFetchError,
        ]
    ]);

    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    } else {
        if (ob_get_level() > 0) {
            @ob_end_flush();
        }
        flush();
    }

    /* ── ENTERPRISE TRACKING CALL FOR FAILURE ── */
    $callingFileUrl = pclBuildCallingFileUrl($requestData);

    $postDataForTracking = [
        'email'            => $email,
        'name'             => $toName,
        'lead_id'          => $requestData['lead_id'] ?? null,
        'reference_id'     => $requestData['lead_id'] ?? '',
        'user_id'          => $requestData['user_id'] ?? null,
        'mobile'           => $requestData['mobile'] ?? '',
        'calling_file_url' => $callingFileUrl,
        'calling_page_url' => $callingFileUrl,
        'attachment_urls'  => $attachmentUrls,
    ];

    // ✅ module_id / submodule_id hardcode kiya — yahan bhi
    pcl_email_enterprise_track($mail, 'failed', [
        'recipient_email' => $email,
        'recipient_name'  => $toName,
        'lead_id'         => $requestData['lead_id'] ?? null,
        'error_message'   => $errorMessage,
        'module_id'       => 10,
        'submodule_id'    => 10,
        'module_key'      => 'sponsor',
        'submodule_key'   => 'sponsor',
        'journey_entity_type' => 'sponsor_brand',
        'journey_entity_id'   => $brandName,
    ]);

    $trackingResult = pcl_email_log_dynamic($mail, !empty($mail->Body) ? $mail->Body : '', $postDataForTracking, [
        'status'            => 'failed',
        'delivery_status'   => 'failed',
        'message'           => $errorMessage,
        'error_message'     => $errorMessage,
        'lead_id'           => $requestData['lead_id'] ?? null,
        'attachment_urls'   => $attachmentUrls,
        'calling_file_url'  => $callingFileUrl,
        'calling_page_url'  => $callingFileUrl,
        'module_id'         => 10,
        'submodule_id'      => 10,
        'module_key'        => 'sponsor',
        'submodule_key'     => 'sponsor',
    ]);

    pcl_write_error_log('email_send_failed', [
        'to'              => $email,
        'lead_id'         => $requestData['lead_id'] ?? null,
        'error'           => $errorMessage,
        'tracking_result' => $trackingResult,
    ]);
}