<?php
include('config.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header("Content-Type: application/json");
date_default_timezone_set("Asia/Kolkata");

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

/* ===============================
   PCL ENTERPRISE EMAIL LOGGING
   Dynamic: controller resolves module/submodule from active_file_name
================================ */
if (file_exists(__DIR__ . '/EmailTrackingApiClient.php')) {
    require_once __DIR__ . '/EmailTrackingApiClient.php';
}

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

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

if (!function_exists('pcl_email_enterprise_track')) {
    function pcl_email_enterprise_track($mail = null, $status = 'sent', array $extra = array()) {
        try {
            $to = array();
            $cc = array();
            $bcc = array();
            $attachments = array();

            if (is_object($mail)) {
                if (method_exists($mail, 'getToAddresses'))  $to  = $mail->getToAddresses();
                if (method_exists($mail, 'getCcAddresses'))  $cc  = $mail->getCcAddresses();
                if (method_exists($mail, 'getBccAddresses')) $bcc = $mail->getBccAddresses();
                if (method_exists($mail, 'getAttachments'))  $attachments = $mail->getAttachments();
            }

            $firstTo = isset($to[0]) ? $to[0] : array('', '');
            $recipientEmail = $extra['recipient_email'] ?? ($firstTo[0] ?? '');
            $recipientName  = $extra['recipient_name']  ?? ($firstTo[1] ?? '');

            $attachmentUrls = $extra['attachment_urls'] ?? array();
            if (is_string($attachmentUrls)) {
                $attachmentUrls = array_values(array_filter(array_map('trim', explode(',', $attachmentUrls))));
            }
            if (!is_array($attachmentUrls)) $attachmentUrls = array();

            $attachmentMeta = array();
            foreach ($attachments as $att) {
                $attachmentMeta[] = array(
                    'name' => $att[2] ?? '',
                    'encoding' => $att[3] ?? '',
                    'type' => $att[4] ?? '',
                    'disposition' => $att[6] ?? ''
                );
            }

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

            $callingFileUrl = $extra['calling_file_url']
                ?? $extra['calling_page_url']
                ?? ($_SERVER['HTTP_REFERER'] ?? '');

            
            $globalContext = array();
            foreach (array('requestData','data','postData','profileData','input','payload') as $gk) {
                if (isset($GLOBALS[$gk]) && is_array($GLOBALS[$gk])) {
                    $globalContext = array_merge($globalContext, $GLOBALS[$gk]);
                }
            }

            $payload = array_merge(array(
                'lead_id'            => $extra['lead_id'] ?? ($globalContext['lead_id'] ?? ($globalContext['id'] ?? ($extra['user_id'] ?? null))),
                'team_id'            => $extra['team_id'] ?? ($globalContext['team_id'] ?? ($globalContext['teamId'] ?? null)),
                'player_id'          => $extra['player_id'] ?? ($globalContext['player_id'] ?? null),
                'user_id'            => $extra['user_id'] ?? ($globalContext['user_id'] ?? null),

                'recipient_email'    => $recipientEmail,
                'recipient_name'     => $recipientName,
                'recipient_mobile'   => $extra['recipient_mobile'] ?? ($extra['mobile'] ?? ($globalContext['mobile'] ?? ($globalContext['phone'] ?? ''))),

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

                'full_email_html'    => $body,
                'full_email_text'    => $extra['full_email_text'] ?? trim(strip_tags((string)$body)),

                'attachment_urls'    => implode(',', $attachmentUrls),
                'attachments_json'   => json_encode(array(
                    'urls' => $attachmentUrls,
                    'mail_attachments' => $attachmentMeta
                ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                'attachment_count'   => count($attachmentUrls) + count($attachmentMeta),

                'current_email_url'  => pcl_email_enterprise_current_url(),
                'calling_file_url'   => $callingFileUrl,
                'calling_page_url'   => $callingFileUrl,
                'direct_email_url'   => pcl_email_enterprise_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'] ?? '',

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

                'request_payload_json' => json_encode($extra, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                'payload_json'         => json_encode($extra, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
            ), $extra);

            // Do not allow caller files to hardcode mapping. Controller resolves from active_file_name.
            unset($payload['module_key'], $payload['submodule_key'], $payload['module_id'], $payload['submodule_id']);
            unset($payload['parent_domain'], $payload['parent_project'], $payload['parent_page_name'], $payload['source_key']);

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

            $ch = curl_init('https://www.procorporateleague.com/pcl_rest/api/v15/email/track/legacy-call');
            curl_setopt_array($ch, array(
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => http_build_query($payload),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 8
            ));
            $response = curl_exec($ch);
            $error = curl_error($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            return array(
                'tracking_status' => ($error === '' && $httpCode >= 200 && $httpCode < 300) ? 'success' : 'failed',
                'http_code' => $httpCode,
                'response' => $response,
                'error' => $error
            );
        } 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['fullName'] ?? '';
        $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'            => $extra['lead_id'],
            '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(),   // ★ FIX — pehle khud apne aap ko call kar raha tha (infinite recursion bug)
            '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(),
            ];
        }
    }
}



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' => $mail->Subject ?? '',
                'status' => 'sent',
                'source' => 'proceed_to_payment'
            ], $extra);
            return EmailTrackingApiClient::trackLegacy($payload);
        }
    } catch (Throwable $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
    return ['success' => false, 'message' => 'Tracking client not available'];
}




function pcl_api_get($url, $timeout = 12) {
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err || !$response) return [];
    $json = json_decode($response, true);
    return is_array($json) ? $json : [];
}

function pcl_safe($value) {
    return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
}

function pcl_first_non_empty(...$values) {
    foreach ($values as $value) {
        if (is_array($value)) continue;
        $value = trim((string)($value ?? ''));
        if ($value !== '') return $value;
    }
    return '';
}

function pcl_decode_json_array($value) {
    if (is_array($value)) return $value;
    $value = trim((string)($value ?? ''));
    if ($value === '') return [];
    $decoded = json_decode($value, true);
    return is_array($decoded) ? $decoded : [];
}

/**
 * Matches the playerDashboard.php AI API handling, but also supports
 * all live response shapes returned by the REST gateway:
 * - {success:true,data:{results:[...]}}
 * - {code:200,results:[...]}
 * - {data:[...]}
 * - direct row object
 */
function pcl_extract_first_result($apiResponse) {
    if (!is_array($apiResponse) || empty($apiResponse)) return [];
    if (!empty($apiResponse['data']['results'][0]) && is_array($apiResponse['data']['results'][0])) return $apiResponse['data']['results'][0];
    if (!empty($apiResponse['results'][0]) && is_array($apiResponse['results'][0])) return $apiResponse['results'][0];
    if (!empty($apiResponse['data'][0]) && is_array($apiResponse['data'][0])) return $apiResponse['data'][0];
    if (!empty($apiResponse[0]) && is_array($apiResponse[0])) return $apiResponse[0];

    $knownKeys = ['raw_ui_json','pcl_ai_rating','raw_final_report_json','raw_selection_probability_json','overall_score','player_type'];
    foreach ($knownKeys as $key) {
        if (array_key_exists($key, $apiResponse)) return $apiResponse;
    }
    return [];
}

function pcl_truthy_status($value) {
    if (is_bool($value)) return $value;
    $value = strtoupper(trim((string)($value ?? '')));
    if ($value === '') return false;
    return in_array($value, ['Y','YES','TRUE','1','GENERATED','DONE','COMPLETED','AI- REPORT CARD GENERATED','REPORT GENERATED'], true);
}

function pcl_money($amount) {
    $amount = (float)($amount ?? 0);
    if ($amount <= 0) return 'To Be Confirmed';
    return '₹' . number_format($amount, 2);
}

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

$leadRequestId = trim((string)($requestData['lead_id'] ?? ''));
if ($leadRequestId === '') {
    echo json_encode(["status_code" => 400, "status" => "failed", "message" => "lead_id is required"]);
    exit;
}

/* ===============================
   LEAD + PROFILE DATA
================================ */
$leadResponse = pcl_api_get('https://procorporateleague.com/pcl_rest/api/v9/user/' . rawurlencode($leadRequestId));
$leadIdData = [];
if (!empty($leadResponse['results']) && (int)($leadResponse['code'] ?? 0) === 200) {
    $leadIdData = $leadResponse['results'][0] ?? [];
}

if (empty($leadIdData)) {
    echo json_encode(["status_code" => 404, "status" => "failed", "message" => "Lead not found"]);
    exit;
}

$mobile = pcl_first_non_empty($leadIdData['phone'] ?? '', $leadIdData['mobile'] ?? '');
$profileResponse = pcl_api_get('https://procorporateleague.com/pcl_rest/api/v9/profile/mobile/' . rawurlencode($mobile));
$profileData = [];
if (!empty($profileResponse['results']) && (int)($profileResponse['code'] ?? 0) === 200) {
    $profileData = $profileResponse['results'][0] ?? [];
}

/* ===============================
   LIVE AI REPORT CARD DATA
   Same source used on playerDashboard.php
================================ */
$aiApi = pcl_api_get('https://www.procorporateleague.com/pcl_rest/api/v9/lead/getAIReportCard/' . rawurlencode($leadRequestId));
$aiRow = pcl_extract_first_result($aiApi);

$uiJson = pcl_decode_json_array($aiRow['raw_ui_json'] ?? '');
$pclRating = pcl_decode_json_array($aiRow['pcl_ai_rating'] ?? '') ?: pcl_decode_json_array($uiJson['pcl_ai_rating'] ?? []);
$finalReport = pcl_decode_json_array($aiRow['raw_final_report_json'] ?? '') ?: pcl_decode_json_array($uiJson['final_report_card'] ?? []);
$selection = pcl_decode_json_array($aiRow['raw_selection_probability_json'] ?? '') ?: pcl_decode_json_array($uiJson['selection_block'] ?? []);
$insights = pcl_decode_json_array($aiRow['ai_performance_insights'] ?? '') ?: pcl_decode_json_array($uiJson['ai_performance_insights'] ?? []);

$aiScore = pcl_first_non_empty($pclRating['overall_rating_out_of_100'] ?? '', $finalReport['overall_score'] ?? '', $aiRow['overall_score'] ?? '');
$aiScore = is_numeric($aiScore) ? number_format((float)$aiScore, 2) : $aiScore;
$aiGrade = pcl_first_non_empty($pclRating['overall_grade'] ?? '', $finalReport['overall_grade'] ?? '', $aiRow['overall_grade'] ?? '');
$playerType = pcl_first_non_empty($finalReport['player_type'] ?? '', $aiRow['player_type'] ?? '', $pclRating['rating_basis'] ?? '', $profileData['primary_role'] ?? 'Corporate Cricketer');
$selectionProbability = pcl_first_non_empty($selection['selection_probability_percent'] ?? '', $selection['probability_percent'] ?? '');
$selectionProbability = is_numeric($selectionProbability) ? number_format((float)$selectionProbability, 2) . '%' : ($selectionProbability ?: 'Under Review');
$selectionBand = pcl_first_non_empty($selection['selection_probability_band'] ?? '', $selection['probability_band'] ?? '', 'Priority Follow-up');

$strengths = [];
if (!empty($insights['strengths']) && is_array($insights['strengths'])) {
    $strengths = array_slice(array_values($insights['strengths']), 0, 3);
}
if (empty($strengths)) {
    $strengths = ['AI-assessed cricket profile', 'Corporate cricket participation readiness', 'PCL Challenger Round eligibility review'];
}

/* ===============================
   AI REPORT BEHAVIOUR
   Two modes exactly like playerDashboard.php:
   1) CricHeroes report-card data available
   2) No CricHeroes report-card data; use PCL video/profile AI review
================================ */
$aiReportFlag   = strtoupper(trim((string)($profileData['ai_report_card_flag'] ?? $leadIdData['ai_report_card_flag'] ?? '')));
$aiReportStage  = strtoupper(trim((string)($profileData['ai_report_card_stage'] ?? $leadIdData['ai_report_card_stage'] ?? '')));
$aiReportResult = strtoupper(trim((string)($profileData['ai_report_card_result'] ?? $leadIdData['ai_report_card_result'] ?? '')));
$isVideoReviewPass = ($aiReportFlag === 'Y' && $aiReportStage === 'AI- REPORT CARD GENERATED' && $aiReportResult === 'PASS');

$cricHeroesUrl = pcl_first_non_empty(
    $profileData['cricheroes_url'] ?? '',
    $profileData['cric_heroes_url'] ?? '',
    $profileData['cricheroes_profile_url'] ?? '',
    $leadIdData['cricheroes_url'] ?? '',
    $leadIdData['cric_heroes_url'] ?? '',
    $aiRow['cricheroes_url'] ?? '',
    $uiJson['cricheroes_url'] ?? ''
);

$cricHeroesReportStatusRaw = pcl_first_non_empty(
    $aiRow['cricheroes_report_generated'] ?? '',
    $aiRow['cric_heroes_report_generated'] ?? '',
    $aiRow['cricheroes_ai_report_card_flag'] ?? '',
    $aiRow['cricheroes_report_status'] ?? '',
    $profileData['cricheroes_report_generated'] ?? '',
    $profileData['cric_heroes_report_generated'] ?? '',
    $profileData['cricheroes_ai_report_card_flag'] ?? '',
    $profileData['cricheroes_report_status'] ?? ''
);

$hasCricHeroesReportData = !empty($finalReport) && (
    stripos(json_encode($finalReport), 'cricheroes') !== false ||
    stripos(json_encode($uiJson), 'cricheroes') !== false ||
    pcl_truthy_status($cricHeroesReportStatusRaw)
);

$hasLiveAiReport = !empty($aiRow) && ($aiScore !== '' || $aiGrade !== '' || !empty($finalReport) || !empty($pclRating));
$reportMode = $hasCricHeroesReportData ? 'CRICHEROES_AI_REPORT' : 'PCL_VIDEO_AI_REPORT';

if (!$hasCricHeroesReportData && $isVideoReviewPass && $aiScore === '') {
    $aiScore = 'PASS';
}
if ($aiGrade === '' && $isVideoReviewPass) {
    $aiGrade = 'Qualified';
}
if ($playerType === '' || strtolower($playerType) === 'corporate cricketer') {
    $playerType = pcl_first_non_empty($profileData['primary_role'] ?? '', $leadIdData['primary_role'] ?? '', $playerType);
}

/* ===============================
   EMAIL VARIABLES
================================ */
$userName = pcl_first_non_empty($leadIdData['full_name'] ?? '', $profileData['name'] ?? '', 'Player');
$email = pcl_first_non_empty($profileData['email'] ?? '', $leadIdData['email'] ?? '');
$city = pcl_first_non_empty($leadIdData['city'] ?? '', $profileData['city'] ?? 'Your City');
$registrationType = pcl_first_non_empty($leadIdData['user_profile'] ?? '', $profileData['user_profile'] ?? 'Individual Player');
$companyName = pcl_first_non_empty($profileData['company_name_individual'] ?? '', $profileData['company_name'] ?? '');
$paymentAmount = (float)($profileData['payment_amount'] ?? 0);
$gst = (float)($profileData['gst'] ?? 0);
$totalAmount = $paymentAmount + $gst;

if ($email === '') {
    echo json_encode(["status_code" => 400, "status" => "failed", "message" => "Email is required"]);
    exit;
}

$invoiceUrl = 'https://www.procorporateleague.com/2026/pcl/playerInvoice.php?id=' . rawurlencode($leadRequestId) . '&mobile=' . rawurlencode($mobile);
$reportUrl  = 'https://www.procorporateleague.com/2026/pcl/playerDashboard.php?id=' . rawurlencode($leadRequestId) . '&mobile=' . rawurlencode($mobile) . '#ai-report';
$pclUrl = 'https://www.procorporateleague.com/';
$cwcUrl = 'https://corporateworldcup.com/';

$trophyImage = 'https://wplspeedqueen.com/email_api/cwctrophy.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';
$firechatImage = 'https://wplspeedqueen.com/email_api/firechat.png';
$merchandiseImage = 'https://wplspeedqueen.com/email_api/cwcmerchandise.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/';

$safeName = pcl_safe($userName);
$safeCity = pcl_safe($city);
$safeRegistrationType = pcl_safe($registrationType);
$safeCompany = pcl_safe($companyName ?: 'Corporate Professional');
$safeScore = pcl_safe($aiScore ?: 'Generated');
$safeGrade = pcl_safe($aiGrade ?: 'AI Rated');
$safePlayerType = pcl_safe($playerType);
$safeSelectionProbability = pcl_safe($selectionProbability);
$safeSelectionBand = pcl_safe($selectionBand);
$safeMobile = pcl_safe($mobile);
$safeLeadId = pcl_safe($leadRequestId);
$safeTotal = pcl_safe(pcl_money($totalAmount));
$safePayment = pcl_safe(pcl_money($paymentAmount));
$safeGst = pcl_safe(pcl_money($gst));
$safeReportModeTitle = pcl_safe($hasCricHeroesReportData ? 'CricHeroes AI Report Card Integrated' : 'PCL AI Video/Profile Review Generated');
$safeReportModeCopy = pcl_safe($hasCricHeroesReportData
    ? 'Your CricHeroes cricket data has been processed with the PCL AI engine and converted into a structured Challenger Round player assessment.'
    : 'CricHeroes report-card data is not available for this profile. Your player assessment has been generated from the PCL video review and submitted player profile, exactly as shown on your Player Dashboard.'
);
$safeCricHeroesStatus = pcl_safe($hasCricHeroesReportData ? 'CricHeroes Report Available' : ($cricHeroesUrl !== '' ? 'CricHeroes URL Added • Report Pending' : 'No CricHeroes Report Data'));

/* ===============================
   SMTP
================================ */
$smtpSql = "SELECT * FROM `smtp_auth_data` WHERE id = 1";
$smtpExe = mysqli_query($conn, $smtpSql);
$smtpRow = mysqli_fetch_assoc($smtpExe);
if (empty($smtpRow)) {
    echo json_encode(["status_code" => 400, "status" => "ERROR", "message" => "SMTP AUTH MISSING"]);
    exit;
}

/* ===============================
   PREMIUM PLAYER REMINDER TEMPLATE
   Converted from teamInvitationEmail.php visual architecture
================================ */
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PCL Challenger Round Payment Follow-up | <?= $safeName ?></title>
</head>
<body style="margin:0;padding:0;background:#edf1f7;font-family:Arial,Helvetica,sans-serif;color:#17233c;">

<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#edf1f7;">
<tr>
<td align="center" style="padding:22px 10px;">

<table role="presentation" width="900" cellpadding="0" cellspacing="0" border="0" style="width:900px;max-width:900px;background:#ffffff;border-radius:20px;overflow:hidden;border:1px solid #d8dfeb;">

<!-- TOP BRAND BAR -->
<tr>
<td style="background:#071d46;padding:18px 26px;border-bottom:3px solid #d6ad45;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td valign="middle">
        <div style="font-family:Georgia,'Times New Roman',serif;font-size:24px;line-height:1.2;color:#ffffff;letter-spacing:.3px;">Pro Corporate League®</div>
        <div style="font-size:11px;line-height:1.5;color:#d6ad45;letter-spacing:1.8px;text-transform:uppercase;margin-top:3px;">PCL AI Report Card • Challenger Round Follow-up</div>
      </td>
      <td align="right" valign="middle" style="font-size:12px;color:#ffffff;line-height:1.6;">
        <?= $safeCity ?> Challenger Round<br>
        Lead ID: <?= $safeLeadId ?>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- HERO IMAGE BANNER -->
<tr>
<td style="background:#071d46;padding:0;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" background="<?= $cwcHeroImage ?>" style="background-image:url('<?= $cwcHeroImage ?>');background-size:cover;background-position:center center;background-repeat:no-repeat;">
    <tr>
      <td style="padding:34px 28px 150px 28px;">
        <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="background:rgba(7,29,70,.88);border:1px solid rgba(214,173,69,.60);border-radius:18px;">
          <tr>
            <td style="padding:18px 20px;">
              <img src="<?= $pclLogo ?>" width="132" alt="Pro Corporate League" style="display:block;width:auto;max-width:132px;max-height:60px;height:auto;border:0;margin-bottom:14px;border:1px solid rgba(214,173,69,.45);background:#071d46;border-radius:10px;padding:10px;">
              <div style="font-size:11px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;">Reminder • Participation Confirmation Pending</div>
              <div style="font-family:Georgia,'Times New Roman',serif;font-size:30px;line-height:1.18;color:#ffffff;font-weight:700;margin-top:6px;">Your PCL AI Report Card<br>Is Ready</div>
              <div style="font-size:14px;line-height:1.6;color:#eef4ff;margin-top:8px;">Complete your registration to secure<br>your Challenger Round participation.</div>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- MAIN HERO -->
<tr>
<td style="background:#071d46;padding:34px 30px 36px 30px;max-width:580px;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="52%" valign="middle" style="padding-right:30px;">
        <div style="font-size:12px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;margin-bottom:12px;">AI Assessment Completed</div>
        <h1 style="margin:0;font-family:Georgia,'Times New Roman',serif;font-size:42px;line-height:1.08;color:#ffffff;font-weight:700;">
          <?= $safeName ?>, Your Participation Confirmation Is Pending
        </h1>
        <div style="margin-top:16px;font-size:17px;line-height:1.65;color:#eef4ff;">
          <?= $safeReportModeCopy ?> The next step is to complete the pending registration formalities for the PCL Challenger Round.
        </div>
        <div style="margin-top:22px;padding:14px 16px;background:rgba(255,255,255,.08);border:1px solid rgba(214,173,69,.45);border-radius:14px;color:#ffffff;font-size:14px;line-height:1.7;">
          This is a follow-up reminder for an AI-qualified player profile. City batches and player slots are processed in phases after registration confirmation.
        </div>
        <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin-top:24px;">
          <tr>
            <td style="padding-right:10px;">
              <a href="<?= $invoiceUrl ?>" style="display:inline-block;background:#d6ad45;color:#071d46;text-decoration:none;font-size:13px;letter-spacing:.6px;text-transform:uppercase;padding:13px 20px;border-radius:999px;font-weight:bold;">Complete Registration</a>
            </td>
            <td>
              <a href="<?= $reportUrl ?>" style="display:inline-block;border:1px solid #d6ad45;color:#ffffff;text-decoration:none;font-size:13px;letter-spacing:.6px;text-transform:uppercase;padding:12px 20px;border-radius:999px;">View AI Report Card</a>
            </td>
          </tr>
        </table>
      </td>
      <td width="42%" valign="middle" align="center">
        <div style="background:#ffffff;border-radius:18px;padding:18px 18px 20px 18px;border:1px solid rgba(214,173,69,.55);">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:14px;">
            <tr>
              <td align="left" valign="middle" style="width:50%;"><img src="wplspeedqueen.com/email_api/pcl_black_logo.png" width="110" alt="PCL" style="display:block;width:auto;max-width:110px;max-height:45px;height:auto;border:0;object-fit:contain;"></td>
              <td align="right" valign="middle" style="width:50%;"><img src="<?= $sonyLivLogo ?>" width="82" alt="Sony LIV" style="display:block;width:auto;max-width:82px;max-height:40px;height:auto;border:0;object-fit:contain;"></td>
            </tr>
          </table>
          <div style="font-size:12px;line-height:1.6;color:#5d6880;text-transform:uppercase;letter-spacing:1px;">PCL AI Rating</div>
          <div style="font-family:Georgia,'Times New Roman',serif;font-size:48px;line-height:1;color:#071d46;font-weight:bold;margin-top:8px;"><?= $safeScore ?></div>
          <div style="font-size:13px;line-height:1.6;color:#5d6880;margin-top:6px;">/100</div>
          <div style="display:inline-block;margin-top:12px;background:#071d46;color:#d6ad45;border-radius:999px;padding:8px 14px;font-size:12px;font-weight:bold;letter-spacing:.8px;text-transform:uppercase;">Grade <?= $safeGrade ?></div>
          <div style="font-size:13px;line-height:1.6;color:#071d46;margin-top:12px;"><?= $safePlayerType ?></div>
        </div>
      </td>
    </tr>
  </table>
</td>
</tr>


<!-- AI SOURCE MODE -->
<tr>
<td style="padding:18px 28px 4px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f7f9fc;border:1px solid #dbe3f1;border-radius:18px;overflow:hidden;">
    <tr>
      <td style="padding:18px 22px;">
        <div style="font-size:12px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;font-weight:bold;">AI Report Source</div>
        <div style="font-family:Georgia,'Times New Roman',serif;font-size:25px;line-height:1.25;color:#071d46;margin-top:5px;"><?= $safeReportModeTitle ?></div>
        <div style="font-size:14px;line-height:1.8;color:#34405c;margin-top:8px;"><?= $safeReportModeCopy ?></div>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- STATUS CARDS -->
<tr>
<td style="padding:24px 28px 4px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="25%" style="padding:6px;"><div style="border:1px solid #e2e7f0;border-radius:15px;padding:16px 12px;min-height:92px;"><div style="font-family:Georgia,'Times New Roman',serif;font-size:20px;color:#071d46;line-height:1.2;"><?= $safeReportModeTitle ?></div><div style="font-size:12px;line-height:1.5;color:#5d6880;margin-top:7px;"><?= $safeCricHeroesStatus ?></div></div></td>
      <td width="25%" style="padding:6px;"><div style="border:1px solid #e2e7f0;border-radius:15px;padding:16px 12px;min-height:92px;"><div style="font-family:Georgia,'Times New Roman',serif;font-size:24px;color:#071d46;line-height:1.1;"><?= $safeCity ?></div><div style="font-size:12px;line-height:1.5;color:#5d6880;margin-top:7px;">City preference</div></div></td>
      <td width="25%" style="padding:6px;"><div style="border:1px solid #e2e7f0;border-radius:15px;padding:16px 12px;min-height:92px;"><div style="font-family:Georgia,'Times New Roman',serif;font-size:24px;color:#071d46;line-height:1.1;"><?= $safeSelectionProbability ?></div><div style="font-size:12px;line-height:1.5;color:#5d6880;margin-top:7px;">Selection probability</div></div></td>
      <td width="25%" style="padding:6px;"><div style="border:1px solid #e2e7f0;border-radius:15px;padding:16px 12px;min-height:92px;"><div style="font-family:Georgia,'Times New Roman',serif;font-size:20px;color:#071d46;line-height:1.2;"><?= $safeSelectionBand ?></div><div style="font-size:12px;line-height:1.5;color:#5d6880;margin-top:7px;">AI follow-up band</div></div></td>
    </tr>
  </table>
</td>
</tr>

<!-- PERSONALIZED MESSAGE -->
<tr>
<td style="padding:22px 36px;background:#ffffff;">
  <div style="font-size:15px;line-height:1.8;color:#24304a;">
    <p style="margin:0 0 14px 0;">Dear <?= $safeName ?>,</p>
    <p style="margin:0 0 14px 0;">This is a premium follow-up reminder from Pro Corporate League®. <?= $safeReportModeCopy ?> Your profile has been evaluated for the upcoming PCL Challenger Round.</p>
    <p style="margin:0 0 14px 0;">Your registration confirmation is currently pending. To secure your participation and enable match allocation processing, please complete the pending registration formalities.</p>
  </div>
</td>
</tr>

<!-- AI SNAPSHOT -->
<tr>
<td style="padding:8px 28px 18px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f7f9fc;border:1px solid #e2e7f0;border-radius:18px;overflow:hidden;">
    <tr>
      <td style="background:#071d46;padding:18px 22px;">
        <div style="font-size:12px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;">Your AI Report Card Snapshot</div>
        <div style="font-family:Georgia,'Times New Roman',serif;font-size:27px;line-height:1.25;color:#ffffff;margin-top:5px;">AI-rated player profile for PCL Challenger Round</div>
      </td>
    </tr>
    <tr>
      <td style="padding:18px 18px 8px 18px;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
          <tr>
            <td width="33.33%" style="padding:6px;"><div style="background:#ffffff;border:1px solid #e2e7f0;border-radius:14px;padding:16px 12px;text-align:center;"><div style="font-size:12px;color:#5d6880;text-transform:uppercase;letter-spacing:.8px;">AI Score</div><div style="font-family:Georgia,'Times New Roman',serif;font-size:30px;color:#071d46;margin-top:8px;"><?= $safeScore ?>/100</div></div></td>
            <td width="33.33%" style="padding:6px;"><div style="background:#ffffff;border:1px solid #e2e7f0;border-radius:14px;padding:16px 12px;text-align:center;"><div style="font-size:12px;color:#5d6880;text-transform:uppercase;letter-spacing:.8px;">Grade</div><div style="font-family:Georgia,'Times New Roman',serif;font-size:30px;color:#071d46;margin-top:8px;">Grade <?= $safeGrade ?></div></div></td>
            <td width="33.33%" style="padding:6px;"><div style="background:#ffffff;border:1px solid #e2e7f0;border-radius:14px;padding:16px 12px;text-align:center;"><div style="font-size:12px;color:#5d6880;text-transform:uppercase;letter-spacing:.8px;">Player Type</div><div style="font-family:Georgia,'Times New Roman',serif;font-size:22px;color:#071d46;margin-top:8px;"><?= $safePlayerType ?></div></div></td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td style="padding:0 24px 22px 24px;font-size:14px;line-height:1.8;color:#24304a;">
        <strong style="color:#071d46;">AI highlights:</strong><br>
        • <?= pcl_safe($strengths[0] ?? '') ?><br>
        • <?= pcl_safe($strengths[1] ?? '') ?><br>
        • <?= pcl_safe($strengths[2] ?? '') ?>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- PAYMENT / NEXT STEP -->
<tr>
<td style="padding:8px 28px 18px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#fffaf0;border:1px solid #f0d99b;border-radius:18px;overflow:hidden;">
    <tr>
      <td style="padding:22px 24px;">
        <div style="font-size:12px;line-height:1.6;color:#a06b00;letter-spacing:2px;text-transform:uppercase;font-weight:bold;">Action Required</div>
        <h2 style="margin:7px 0 8px 0;font-family:Georgia,'Times New Roman',serif;font-size:30px;line-height:1.22;color:#071d46;font-weight:700;">Complete Your Registration Confirmation</h2>
        <div style="font-size:14px;line-height:1.8;color:#34405c;">Pending amount details are available on your invoice page. If already paid, please ignore this reminder and our team will update your profile status shortly.</div>
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:16px;">
          <tr>
            <td width="33.33%" style="padding:6px;"><div style="background:#ffffff;border:1px solid #f0d99b;border-radius:14px;padding:14px 10px;text-align:center;"><div style="font-size:12px;color:#7a5a16;">Base Amount</div><div style="font-family:Georgia,'Times New Roman',serif;font-size:22px;color:#071d46;margin-top:6px;"><?= $safePayment ?></div></div></td>
            <td width="33.33%" style="padding:6px;"><div style="background:#ffffff;border:1px solid #f0d99b;border-radius:14px;padding:14px 10px;text-align:center;"><div style="font-size:12px;color:#7a5a16;">GST</div><div style="font-family:Georgia,'Times New Roman',serif;font-size:22px;color:#071d46;margin-top:6px;"><?= $safeGst ?></div></div></td>
            <td width="33.33%" style="padding:6px;"><div style="background:#071d46;border:1px solid #071d46;border-radius:14px;padding:14px 10px;text-align:center;"><div style="font-size:12px;color:#d6ad45;">Total Payable</div><div style="font-family:Georgia,'Times New Roman',serif;font-size:22px;color:#ffffff;margin-top:6px;"><?= $safeTotal ?></div></div></td>
          </tr>
        </table>
        <div style="text-align:center;margin-top:20px;">
          <a href="<?= $invoiceUrl ?>" style="display:inline-block;background:#d6ad45;color:#071d46;text-decoration:none;font-size:13px;letter-spacing:.6px;text-transform:uppercase;padding:14px 24px;border-radius:999px;font-weight:bold;margin:4px;">Complete Payment / Registration</a>
          <a href="<?= $reportUrl ?>" style="display:inline-block;border:1px solid #071d46;color:#071d46;text-decoration:none;font-size:13px;letter-spacing:.6px;text-transform:uppercase;padding:13px 22px;border-radius:999px;margin:4px;">View AI Report Card</a>
        </div>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- PLAYER JOURNEY -->
<tr>
<td style="padding:12px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#071d46;border-radius:18px;overflow:hidden;">
    <tr>
      <td style="padding:24px 24px 10px 24px;">
        <div style="font-size:12px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;">Why Confirm Now</div>
        <h2 style="margin:8px 0 0 0;font-family:Georgia,'Times New Roman',serif;font-size:28px;line-height:1.2;color:#ffffff;font-weight:700;">Your Challenger Round Pathway Starts After Registration Confirmation</h2>
      </td>
    </tr>
    <tr>
      <td style="padding:10px 18px 22px 18px;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
          <tr>
            <td width="25%" style="padding:6px;"><div style="background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);border-radius:14px;padding:15px 10px;text-align:center;"><div style="font-size:24px;color:#d6ad45;font-family:Georgia,'Times New Roman',serif;">AI</div><div style="font-size:11px;line-height:1.5;color:#eaf1ff;">Report Card Generated</div></div></td>
            <td width="25%" style="padding:6px;"><div style="background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);border-radius:14px;padding:15px 10px;text-align:center;"><div style="font-size:24px;color:#d6ad45;font-family:Georgia,'Times New Roman',serif;">7</div><div style="font-size:11px;line-height:1.5;color:#eaf1ff;">Challenger Round Matches</div></div></td>
            <td width="25%" style="padding:6px;"><div style="background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);border-radius:14px;padding:15px 10px;text-align:center;"><div style="font-size:24px;color:#d6ad45;font-family:Georgia,'Times New Roman',serif;">Rank</div><div style="font-size:11px;line-height:1.5;color:#eaf1ff;">Player Rankings & Visibility</div></div></td>
            <td width="25%" style="padding:6px;"><div style="background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);border-radius:14px;padding:15px 10px;text-align:center;"><div style="font-size:24px;color:#d6ad45;font-family:Georgia,'Times New Roman',serif;">CWC</div><div style="font-size:11px;line-height:1.5;color:#eaf1ff;">Corporate World Cup Pathway</div></div></td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td style="padding:0 24px 24px 24px;font-size:13px;line-height:1.8;color:#dfe8ff;">
        The PCL Challenger Round is designed for working professionals who want structured competitive cricket, AI-backed performance analysis and visibility in the corporate cricket ecosystem.
      </td>
    </tr>
  </table>
</td>
</tr>


<!-- PCL LEGACY SECTION FROM TEAM INVITATION TEMPLATE -->
<tr>
<td style="padding:12px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border:1px solid #e2e7f0;border-radius:18px;overflow:hidden;background:#071d46;">
    <tr>
      <td style="padding:24px 24px 12px 24px;">
        <div style="font-size:12px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;">Celebrity Trust & Corporate Credibility</div>
        <h2 style="margin:8px 0 10px 0;font-family:Georgia,'Times New Roman',serif;font-size:28px;line-height:1.2;color:#ffffff;font-weight:700;">15 Years Of Building Corporate Teams Beyond The Workplace</h2>
        <div style="font-size:14px;line-height:1.8;color:#eaf1ff;">
          Pro Corporate League has engaged 500+ corporate teams and worked alongside global cricket personalities to create one of India's most visible corporate cricket ecosystems.
        </div>
      </td>
    </tr>
    <tr>
      <td style="padding:10px 24px 0 24px;">
        <img src="<?= $celebrityImage ?>" width="852" alt="PCL Celebrity Engagement" style="display:block;width:100%;max-width:852px;height:auto;border:0;border-radius:14px;">
      </td>
    </tr>
    <tr>
      <td style="padding:14px 24px 24px 24px;font-size:13px;line-height:1.7;color:#dfe8ff;">
        A credibility-led ecosystem supported by cricket legends, corporate leaders and national-level corporate sporting stories.
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- CHRIS GAYLE AUTHENTICITY + CHAMPIONS VIDEO -->
<tr>
<td style="padding:12px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border:1px solid #d6ad45;border-radius:18px;overflow:hidden;background:#fff8e4;">
    <tr>
      <td width="58%" valign="middle" style="padding:24px;">
        <div style="font-size:12px;line-height:1.6;color:#a17300;letter-spacing:2px;text-transform:uppercase;">PCL Season 11 Closing Ceremony</div>
        <h2 style="margin:8px 0 10px 0;font-family:Georgia,'Times New Roman',serif;font-size:26px;line-height:1.25;color:#071d46;font-weight:700;">Chris Gayle Presence Added Authenticity To The Corporate Champions Celebration</h2>
        <div style="font-size:14px;line-height:1.8;color:#24304a;">
          Chris Gayle was present during the PCL Season 11 closing ceremony, recognising corporate champions and strengthening the credibility of the Pro Corporate League ecosystem.
        </div>
      </td>
      <td width="42%" valign="middle" align="center" style="padding:18px;">
        <a href="<?= $championsVideo ?>" style="text-decoration:none;">
          <img src="<?= $chrisGayleImage ?>" width="330" alt="Chris Gayle at PCL Season 11 Closing Ceremony" style="display:block;width:100%;max-width:330px;height:auto;border:0;border-radius:14px;">
          <div style="display:inline-block;margin-top:12px;background:#071d46;color:#ffffff;font-size:12px;letter-spacing:.6px;text-transform:uppercase;padding:10px 16px;border-radius:999px;">Watch Champions Highlights</div>
        </a>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- SONY LIV AUTHENTICITY -->
<tr>
<td style="padding:12px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border:1px solid #e2e7f0;border-radius:18px;overflow:hidden;background:#ffffff;">
    <tr>
      <td width="28%" valign="middle" align="center" style="padding:22px;background:#f7f9fc;">
        <img src="<?= $sonyLivLogo ?>" width="120" alt="Sony LIV" style="display:block;width:120px;max-width:120px;height:auto;border:0;margin:0 auto;">
      </td>
      <td width="72%" valign="middle" style="padding:22px;">
        <div style="font-size:12px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;">Broadcast Visibility</div>
        <h2 style="margin:6px 0 8px 0;font-family:Georgia,'Times New Roman',serif;font-size:25px;line-height:1.25;color:#071d46;font-weight:700;">PCL On Sony LIV</h2>
        <div style="font-size:14px;line-height:1.8;color:#34405c;">
          Pro Corporate League's Eleven 11 highlight property has been showcased through the Sony LIV ecosystem, adding broadcast credibility and visibility for participating corporate teams and players.
        </div>
        <a href="<?= $sonyLivCoverageUrl ?>" style="display:inline-block;margin-top:12px;background:#071d46;color:#ffffff;text-decoration:none;font-size:12px;letter-spacing:.6px;text-transform:uppercase;padding:10px 16px;border-radius:999px;">View Sony LIV Coverage</a>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- CLOSING COPY -->
<tr>
<td style="padding:18px 36px 12px 36px;background:#ffffff;">
  <div style="font-size:15px;line-height:1.8;color:#24304a;">
    <p style="margin:0 0 14px 0;">We recommend completing your registration confirmation at the earliest so the operations team can move your profile into the next allocation stage.</p>
    <p style="margin:0 0 14px 0;">For any assistance, simply reply to this email and our team will help you with the next step.</p>
    <p style="margin:18px 0 0 0;">Warm regards,<br><br>Team Pro Corporate League®<br>Corporate Cricket Ecosystem<br><br>📧 <a href="mailto:pcl@procorporateleague.com" style="color:#071d46;text-decoration:none;">pcl@procorporateleague.com</a><br>🌐 <a href="<?= $pclUrl ?>" style="color:#071d46;text-decoration:none;">www.procorporateleague.com</a></p>
    <img src="<?= $trophyImage ?>" width="110" alt="Corporate World Cup Trophy" style="display:block;width:110px;height:auto;border:0;margin:16px 0 0 0;">
  </div>
</td>
</tr>

<!-- CTA FOOTER -->
<tr>
<td style="background:#071d46;padding:26px 28px;text-align:center;">
  <div style="font-family:Georgia,'Times New Roman',serif;font-size:26px;line-height:1.25;color:#ffffff;margin-bottom:8px;">Confirm Your PCL Challenger Round Participation</div>
  <div style="font-size:14px;line-height:1.7;color:#dfe8ff;margin-bottom:20px;">Your AI Report Card has been generated. Complete registration to move ahead in the participation workflow.</div>
  <a href="<?= $invoiceUrl ?>" style="display:inline-block;background:#d6ad45;color:#071d46;text-decoration:none;font-size:13px;letter-spacing:.6px;text-transform:uppercase;padding:13px 22px;border-radius:999px;margin:4px;font-weight:bold;">Complete Registration</a>
  <a href="<?= $reportUrl ?>" style="display:inline-block;border:1px solid #d6ad45;color:#ffffff;text-decoration:none;font-size:13px;letter-spacing:.6px;text-transform:uppercase;padding:12px 22px;border-radius:999px;margin:4px;">View AI Report Card</a>
  <div style="font-size:11px;line-height:1.8;color:#b9c6df;margin-top:20px;">
    15+ Years Building Corporate Cricket • 500+ Corporate Teams • 3000+ Matches Conducted<br>
    Chris Gayle 2026 • Jonty Rhodes 2025 • PCL on Sony LIV<br>
    Pro Corporate League® • India's Corporate Cricket Ecosystem<br><br>
    <a href="https://corporateworldcup.com/" style="color:#d6ad45;text-decoration:none;">corporateworldcup.com</a> &nbsp;|&nbsp;
    <a href="https://www.roadtocorporateworldcup.com/" style="color:#d6ad45;text-decoration:none;">roadtocorporateworldcup.com</a><br>
    <a href="https://www.procorporateleague.com/pcl/media/chris-gayle-universe-boss-corporate-cricket-india/" style="color:#d6ad45;text-decoration:none;">Chris Gayle at PCL</a> &nbsp;|&nbsp;
    <a href="https://www.procorporateleague.com/pcl/media/jonty-rhodes-goat-pcl-corporate-cricket-india/" style="color:#d6ad45;text-decoration:none;">Jonty Rhodes at PCL</a><br>
    <a href="https://www.procorporateleague.com/pcl/media/pcl-legacy-corporate-cricket-india/" style="color:#d6ad45;text-decoration:none;">PCL Legacy</a> &nbsp;|&nbsp;
    <a href="https://www.procorporateleague.com/ai/pcl-ai-sports-tech-platform/" style="color:#d6ad45;text-decoration:none;">PCL AI Sports Tech</a><br>
    Lead ID: <?= $safeLeadId ?> • Mobile: <?= $safeMobile ?><br>
    © 2026 Pro Corporate League. This is an official PCL Challenger Round payment follow-up reminder.
  </div>
</td>
</tr>

</table>
</td>
</tr>
</table>
</body>
</html>
<?php
$emailBody = ob_get_clean();

$subject = trim((string)($requestData['subject'] ?? ''));
if ($subject === '') {
    $subject = 'Reminder: Complete Your PCL Challenger Round Registration';
}

/* ===============================
   SEND EMAIL
================================ */
$mail = new PHPMailer(true);
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 = true;

    $mail->CharSet  = 'UTF-8';
    $mail->Encoding = 'base64';
    $mail->isHTML(true);

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

    if (!empty($requestData['cc']) && is_array($requestData['cc'])) {
        foreach ($requestData['cc'] as $cc) {
            $ccEmail = trim((string)($cc['email'] ?? ''));
            $ccName = trim((string)($cc['name'] ?? ''));
            if ($ccEmail !== '') $mail->addCC($ccEmail, $ccName);
        }
    } else {
        $mail->addCC('sachin.gupta@procorporateleague.com', 'Sachin Gupta');
        $mail->addCC('sachin.gupta@corporateworldcup.com', 'Sachin Gupta');
    }

    $mail->Subject = $subject;
    $mail->Body = $emailBody;
    $mail->AltBody = "Reminder: Your PCL AI Report Card is ready. Please complete your Challenger Round registration: " . $invoiceUrl . " | Report: " . $reportUrl;
    $mail->send();

    
        $pclEmailTrackingResult = pcl_email_enterprise_track($mail, 'sent');
        echo json_encode([
                "status_code" => 200,
                "status" => "success",
                "message" => "Premium PCL Challenger Round payment reminder sent successfully",
                "lead_id" => $leadRequestId,
                "email" => $email,
                "ai_score" => $aiScore,
                "ai_grade" => $aiGrade,
                'module_id' => 4,
                'submodule_id' => 4,
                'module_key' => 'payment_reminder',
                'submodule_key' => 'payment_reminder',
        ]);


        $tracking = pcl_track_email_if_available($mail, [
            'lead_id' => $leadRequestId,
            'mobile' => $mobile,
            'recipient_email' => $email,
            'recipient_name' => $userName,
            'subject' => $subject,
            'module_id' => 4,
            'submodule_id' => 4,
            'module_key' => 'payment_reminder',
            'submodule_key' => 'payment_reminder',
            'active_file_name' => basename(__FILE__),
            'calling_file_url' => $_SERVER['HTTP_REFERER'] ?? '',
            'full_email_html' => $emailBody
        ]);






} 
catch (Exception $e) {
    
    if (isset($mail)) {
        pcl_email_enterprise_track($mail, 'failed', array('error_message' => (!empty($mail->ErrorInfo) ? $mail->ErrorInfo : $e->getMessage())));
    }
echo json_encode([
        "status_code" => 500,
        "status" => "error",
        "message" => $mail->ErrorInfo
    ]);
}
