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

include('config.php');

date_default_timezone_set("Asia/Kolkata");

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

/* ===============================★ SABSE UPAR — REQUEST DATA + IDs (function definitions se pehle taaki $GLOBALS mein already available rahe)================================ */
$requestData = json_decode(file_get_contents("php://input"), true);

//echo "<pre>"; print_r($requestData); die;

$teamId = $requestData['lead_id'] ?? '';
$leadId = $requestData['lead_id'] ?? $requestData['reference_id'] ?? '';  
$ccList = $requestData['cc']      ?? [];
$email  = $requestData['email']   ?? '';

// echo "<pre>"; print_r($teamId); die;

/* ── POST DATA — ★ Sabse upar shift kiya ── */
$postData = [
    "subject"            => $requestData['subject']           ?? 'Registration Confirmed – Pro Corporate League',
    "email"              => $requestData['email']             ?? '',
    "name"               => $requestData['full_name']         ?? 'PCL',
    "city"               => $requestData['city']              ?? $requestData['city_id'] ?? '',
    "reference_id"       => $requestData['reference_id']      ?? '',
    "registration_type"  => $requestData['registration_type'] ?? '',
    "mobile"             => $requestData['mobile']            ?? '',
    "user_id"            => $requestData['userId']            ?? '',
    "company_name"       => $requestData['company_name']      ?? '',
    "team_name"          => $requestData['team_name']         ?? '',
    "person_name"        => $requestData['person_name']       ?? '',
    "team_type"          => $requestData['team_type']         ?? '',
    "sector"             => $requestData['corporate_sector']  ?? '',
    "availability_window"=> $requestData['availability_window'] ?? '',
    "team_logo"          => $requestData['team_logo']         ?? '',
];

// ✅ FIX — $subject used later (tracking calls) but was never defined anywhere in the file.
// Defining it right after $postData so every later reference to $subject is safe.
$subject = $postData['subject'];

// echo "<pre>"; print_r($postData); die;

/* ===============================
   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'] ?? 'www.procorporateleague.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'] ?? 'www.procorporateleague.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['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'            => $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(),   // ★ 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' => $leadId ?? null,
                'recipient_email' => $extra['recipient_email'] ?? '',
                'recipient_name' => $extra['recipient_name'] ?? '',
                'subject' => $mail->Subject ?? '',
                'status' => 'sent',
                'source' => 'cric_heroes_profile_reminder'
            ], $extra);
            return EmailTrackingApiClient::trackLegacy($payload);
        }
    } catch (Throwable $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
    return ['success' => false, 'message' => 'Tracking client not available'];
}



$filePath   = "https://www.procorporateleague.com/2026/pcl/assets/mail_image/";
$imgVersion = time();

/* ── PCL OVERALL STATS ── */
$statscurl = curl_init();
curl_setopt_array($statscurl, [
    CURLOPT_URL            => 'https://procorporateleague.com/pcl_rest/api/v1/pcl/stats',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => '',
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => 'GET'
]);
$statsResponse = curl_exec($statscurl);
curl_close($statscurl);
$statsJson = json_decode($statsResponse, true);
$statsArrayData = [
    'total_matches_played'  => $statsJson['results'][0]['Total_Matches_Played']  ?? 0,
    'total_runs_Scored'     => $statsJson['results'][0]['Total_Runs_Scored']     ?? 0,
    'total_wickets_Claimed' => $statsJson['results'][0]['Total_Wickets_Claimed'] ?? 0,
    'total_hundreds'        => $statsJson['results'][0]['Total_Hundreds']        ?? 0,
    'total_fifties'         => $statsJson['results'][0]['Total_Fifties']         ?? 0,
];

// if (empty($postData['email'])) {
//   pcl_write_error_log('validation_failed', ['reason' => 'Email missing', 'postData' => $postData]);
//     echo json_encode([
//         "status_code" => 400,
//         "status"      => "failed",
//         "message"     => "Email is required"
//     ]);
//     exit;
// }

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://procorporateleague.com/pcl_rest/api/v9/profile/mobile/'.$postData['mobile']??'',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);

curl_close($curl);
//echo $response;
$profileCurlData = json_decode($response, true);
$profileData='';
if(!empty($profileCurlData) && !empty($profileCurlData['results']) && $profileCurlData['code'] === 200)
{
    $profileData = $profileCurlData['results'][0]??'';
} 

// echo "<pre>"; print_r($profileData); die;


/* ── ALL CITIES (single curl) ── */
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL            => 'https://www.procorporateleague.com/pcl_rest/api/v9/corporate/getAllCities',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => '',
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 8,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => 'GET',
]);
$response = curl_exec($curl);
curl_close($curl);

$citiesJson = json_decode($response, true);
$city = '';

$selectedCity = !empty($postData['city'])
    ? $postData['city']
    : ($profileData['city'] ?? '');

$selectedCity = trim((string)$selectedCity);

if (!empty($citiesJson['results'])) {
    foreach ($citiesJson['results'] as $row) {
        if (strcasecmp(trim($row['city_name']), $selectedCity) === 0) {
            $city = $row['city_name'];
            break;
        }
    }
}

// echo "<pre>"; print_r($city); die;




/* ── ALL SECTORS (single curl) ── */
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL            => 'https://www.procorporateleague.com/pcl_rest/api/v9/corporate/getAllSectors',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => '',
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 8,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => 'GET',
]);
$response = curl_exec($curl);
curl_close($curl);

$sectorsJson = json_decode($response, true);
$sector = '';
if (!empty($sectorsJson['results'])) {
    foreach ($sectorsJson['results'] as $row) {
        if ($row['id'] == $postData['sector']) {
            $sector = $row['sector_name'];
            break;
        }
    }
}

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

/* ── BUILD TEMPLATE VARIABLES ── */
$pclLogo     = 'https://www.procorporateleague.com/2026/pcl/Imp_PCL_Logo_Black.png';
$sonyLivLogo = 'https://www.procorporateleague.com/2026/pcl/SonyLIV_2020.png';

$teamName   = trim($postData['team_name'] ?: ($postData['company_name'] ?: 'Your Team'));
$cityName   = trim($city  ?: 'Your City');
$sectorName = trim($sector ?: 'Your Sector');
$safeTeam   = htmlspecialchars($teamName,   ENT_QUOTES, 'UTF-8');
$safeCity   = htmlspecialchars($cityName,   ENT_QUOTES, 'UTF-8');
$safeSector = htmlspecialchars($sectorName, ENT_QUOTES, 'UTF-8');

$teamLogoRaw = trim($postData['team_logo'] ?? '');
if ($teamLogoRaw !== '' && !preg_match('/^https?:\/\//i', $teamLogoRaw)) {
    $teamLogoRaw = 'https://www.procorporateleague.com/2026/pcl/assets/team_logo/' . ltrim($teamLogoRaw, '/');
}
$teamLogoUrl = $teamLogoRaw !== '' ? $teamLogoRaw : $pclLogo;
$teamLogoAlt = $safeTeam . ' Logo';

$user_name           = htmlspecialchars($postData['name']);
$user_email          = htmlspecialchars($postData['email']);
$reference_id        = htmlspecialchars($postData['reference_id']);
$registration_type   = htmlspecialchars($postData['registration_type']);
$user_mobile         = htmlspecialchars($postData['mobile']);
$availability_window = htmlspecialchars($postData['availability_window']);
$team_type           = htmlspecialchars($postData['team_type']);
$team_name           = htmlspecialchars($postData['team_name']);
$advanceAmount       = 50000;

$cta_link = "https://www.procorporateleague.com/2026/pcl/eleven11.php?lead_id=" . urlencode($postData['reference_id']) . "&id=" . urlencode($postData['user_id']);

if (!empty($registration_type) && $registration_type == 'team') {
    $team         = 'team';
    $company_name = $postData['company_name'];
    $person_name  = $postData['name'];
} else {
    $team         = 'individual';
    $company_name = $postData['company_name'];
    $person_name  = $user_name;
}

$teamDashboardUrl = 'https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile.php?team_id=' . rawurlencode((string)$teamId) . '&team_name=' . rawurlencode($teamName);
$reserveUrl       = 'https://www.procorporateleague.com/pcl/team-register/';
$cwcUrl           = 'https://corporateworldcup.com/';
$pclUrl           = 'https://www.procorporateleague.com/';

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

ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Corporate World Cup™ Invitation | <?= $safeTeam ?></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;">Corporate World Cup™</div>
        <div style="font-size:11px;line-height:1.5;color:#d6ad45;letter-spacing:1.8px;text-transform:uppercase;margin-top:3px;">Team Registration Confirmed</div>
      </td>
      <td align="right" valign="middle" style="font-size:12px;color:#ffffff;line-height:1.6;">
        <?= $safeCity ?> Qualification Round<br>
        <?= $safeSector ?> Category
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- CORPORATE WORLD CUP HERO 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,.86);border:1px solid rgba(214,173,69,.55);border-radius:18px;">
          <tr>
            <td style="padding:16px 18px;">
              
              <img src="https://wplspeedqueen.com/email_api/pcl_black_logo.png" width="145" alt="<?= $teamLogoAlt ?>" style="display:block;width:auto;max-width:145px;max-height:62px;height:auto;border:0;object-fit:contain;margin-bottom:14px;background:#ffffff;border-radius:10px;padding:8px;">
              
              <div style="font-size:11px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;">Out of 500+ Corporate Teams Evaluated</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;"><?= $safeTeam ?></div>
              <div style="font-size:14px;line-height:1.6;color:#eef4ff;margin-top:8px;">Corporate World Cup™ Qualification Round</div>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- HERO -->
<tr>
<td style="background:#071d46;padding:34px 30px 36px 30px;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="58%" valign="middle" style="padding-right:24px;">
        <div style="font-size:12px;line-height:1.6;color:#d6ad45;letter-spacing:2px;text-transform:uppercase;margin-bottom:12px;">Out of 500+ Corporate Teams Evaluated</div>
        <h1 style="margin:0;font-family:Georgia,'Times New Roman',serif;font-size:44px;line-height:1.08;color:#ffffff;font-weight:700;">
          <?= $teamName ?> Has Been Registered
        </h1>
        <div style="margin-top:16px;font-size:18px;line-height:1.6;color:#eef4ff;">
          For the inaugural Corporate World Cup™ Qualification 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;">
          Only 8 corporate teams per city. Only 1 team per sector. Top 2 city teams qualify for the Corporate World Cup™ National Finals ecosystem.
        </div>



        <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin-top:24px;">
          <tr>
              <td style="padding-right:12px;">
                  <a href="https://www.procorporateleague.com/pcl/team-register/pcl-team-dashboard.php?mobile=<?php echo urlencode($user_mobile); ?>&lead_id=<?php echo urlencode($reference_id); ?>"
                    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:30px;">
                     Reserve Slot
                  </a>
              </td>

              <td>
                  <a href="https://www.procorporateleague.com/pcl/team-register/teamInvoice.php?mobile=<?php echo urlencode($user_mobile ); ?>&lead_id=<?php echo urlencode($reference_id); ?>&amount=<?php echo $advanceAmount; ?>"
                    style="display:inline-block;border:1px solid #d6ad45;color:#ffffff;text-decoration:none;font-size:13px;letter-spacing:.6px;text-transform:uppercase;padding:13px 20px;border-radius:30px;">
                      Confirm Slot
                  </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="https://wplspeedqueen.com/email_api/pcl_black_logo.png" width="120" alt="<?= $teamLogoAlt ?>" style="display:block;width:auto;max-width:120px;max-height:50px;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>
          <img src="<?= $trophyImage ?>" width="300" alt="Corporate World Cup Trophy" style="display:block;width:100%;max-width:300px;height:auto;border:0;margin:0 auto;">
          <div style="font-size:12px;line-height:1.6;color:#071d46;margin-top:10px;">
            Only 2 teams from <?= $safeCity ?> will qualify for the National Finals ecosystem.
          </div>
        </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:27px;color:#071d46;line-height:1.1;">500+</div>
          <div style="font-size:12px;line-height:1.5;color:#5d6880;margin-top:7px;">Corporate teams evaluated</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;"><?= $safeTeam ?></div>
          <div style="font-size:12px;line-height:1.5;color:#5d6880;margin-top:7px;">Registered for Participation</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;">Category Protection</div>
          <div style="font-size:12px;line-height:1.5;color:#5d6880;margin-top:7px;">Only one <?= $safeSector ?> team per city</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;">Reservation Open</div>
          <div style="font-size:12px;line-height:1.5;color:#5d6880;margin-top:7px;">Before public category allocation</div>
        </div>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- DETAILS + NOTE -->
<tr>
<td style="padding:12px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="50%" valign="top" style="padding-right:7px;">
        <table width="100%" style="background:#f8fbff;border:1px solid #d9e6ff;border-radius:6px;">
          <tr>
            <td style="padding:12px;">
              <h3 style="margin:0 0 8px;color:#0b1f4d;">Registration Details</h3>
              <p style="margin:4px 0;"><strong>Registration Type:</strong> <?= ucwords($team) ?></p>
              <p style="margin:4px 0;"><strong>Full Name:</strong> <?= ucwords($person_name) ?></p>
              <p style="margin:4px 0;"><strong>Company Name:</strong> <?= ucwords($company_name) ?></p>
              <?php if (!empty($postData['team_name'])): ?>
                <p style="margin:4px 0;"><strong>Team Name:</strong> <?= ucwords($postData['team_name']) ?></p>
              <?php endif; ?>
              <p style="margin:4px 0;"><strong>Registered Email:</strong> <?= $user_email ?></p>
              <p style="margin:4px 0;"><strong>Registered Mobile:</strong> <?= $user_mobile ?></p>
              <p style="margin:4px 0;"><strong>City:</strong> <?= htmlspecialchars($city) ?></p>
              <?php if(!empty($sector)):?>
                <p style="margin:4px 0;"><strong>Sector:</strong> <?= htmlspecialchars($sector) ?></p>
              <?php else: ?>
                <p style="margin:4px 0;"><strong>Sector:</strong> <?= htmlspecialchars($requestData['corporate_sector']??'') ?></p>
              <?php endif;?>    
              
              <p style="margin:4px 0;"><strong>Reference ID:</strong> <?= $reference_id ?></p>
            </td>
          </tr>
        </table>
      </td>
      <td width="50%" valign="top" style="padding-left:7px;">
        <table width="100%" style="background:#fff8e8;border:1px solid #ffe2a8;border-radius:6px;">
          <tr>
            <td style="padding:12px;">
              <h3 style="margin:0 0 8px;color:#7a4d00;">Important Note</h3>
              <p style="margin:4px 0;"><strong>Reference ID:</strong> <?= $reference_id ?></p>
              <p style="margin:4px 0;">• Keep your <strong>Reference ID</strong> handy for all future communication</p>
              <p style="margin:4px 0;">• Ensure your email and WhatsApp remain active for updates</p>
              <p style="margin:4px 0;">• Limited slots per city – priority is given on a first-come basis</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- WHY THIS MATTERS -->
<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;">
    <tr>
      <td style="background:#f7f9fc;padding:20px 24px;">
        <h2 style="margin:0;font-family:Georgia,'Times New Roman',serif;font-size:26px;line-height:1.2;color:#071d46;font-weight:700;">Why This Matters</h2>
      </td>
    </tr>
    <tr>
      <td style="padding:22px 24px;font-size:15px;line-height:1.8;color:#24304a;">
        The Corporate World Cup™ has been created to provide organizations with a platform that combines employee engagement, leadership participation, employer branding and competitive sport within a professionally managed national framework.
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- PARTICIPATION INCLUDES -->
<tr>
<td style="padding:12px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="58%" valign="top" style="padding-right:14px;">
        <div style="border:1px solid #e2e7f0;border-radius:18px;padding:22px 24px;">
          <h2 style="margin:0 0 16px 0;font-family:Georgia,'Times New Roman',serif;font-size:25px;line-height:1.2;color:#071d46;font-weight:700;">Participation Includes</h2>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size:14px;line-height:1.8;color:#24304a;">
            <tr><td style="padding:5px 0;">• 18 matches across three formats</td></tr>
            <tr><td style="padding:5px 0;">• Team merchandise for 30 players</td></tr>
            <tr><td style="padding:5px 0;">• Live match coverage and highlights</td></tr>
            <tr><td style="padding:5px 0;">• AI-powered team and player rankings</td></tr>
            <tr><td style="padding:5px 0;">• Corporate storytelling and employer branding opportunities</td></tr>
            <tr><td style="padding:5px 0;">• Eligibility to qualify for the Corporate World Cup™ National Finals ecosystem</td></tr>
          </table>
        </div>
      </td>
      <td width="42%" valign="top">
        <div style="border:1px solid #e2e7f0;border-radius:18px;overflow:hidden;background:#f7f9fc;">
          <img src="<?= $merchandiseImage ?>" width="340" alt="Corporate World Cup Team Merchandise" style="display:block;width:100%;height:auto;border:0;">
          <div style="padding:16px 18px;font-size:13px;line-height:1.7;color:#24304a;">
            30-player team merchandise package included as part of the qualification journey.
          </div>
        </div>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- EXCLUSIVITY + QUALIFICATION -->
<tr>
<td style="padding:12px 28px;background:#ffffff;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="50%" valign="top" style="padding-right:7px;">
        <div style="border:1px solid #e2e7f0;border-radius:18px;padding:22px 24px;min-height:220px;">
          <h2 style="margin:0 0 14px 0;font-family:Georgia,'Times New Roman',serif;font-size:24px;line-height:1.2;color:#071d46;font-weight:700;">Category Exclusivity</h2>
          <div style="font-size:14px;line-height:1.8;color:#24304a;">
            As part of the Corporate World Cup™ structure, only one corporate team per sector is permitted in each city. This ensures category exclusivity throughout the qualification journey.
            <br><br>
            Once a sector is allocated, it is closed for the remainder of the qualification cycle.
          </div>
        </div>
      </td>
      <td width="50%" valign="top" style="padding-left:7px;">
        <div style="border:1px solid #e2e7f0;border-radius:18px;padding:22px 24px;min-height:220px;">
          <h2 style="margin:0 0 14px 0;font-family:Georgia,'Times New Roman',serif;font-size:24px;line-height:1.2;color:#071d46;font-weight:700;">Qualification Structure</h2>
          <div style="font-size:14px;line-height:1.9;color:#24304a;">
            • Only 8 corporate teams per city<br>
            • Only 1 corporate team per sector<br>
            • Top 2 city teams qualify for the Corporate World Cup™ National Finals ecosystem<br>
            • City champions receive complimentary entry into the National Finals structure
          </div>
        </div>
      </td>
    </tr>
  </table>
</td>
</tr>

<!-- CELEBRITY TRUST + PCL 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:#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 -->
<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 -->
<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:#a17300;letter-spacing:2px;text-transform:uppercase;">Broadcast Visibility</div>
        <h2 style="margin:8px 0 10px 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:#24304a;">
          Pro Corporate League's Eleven 11 highlight property has been showcased through the Sony LIV ecosystem, adding broadcast credibility and visibility to participating corporate teams.
        </div>
        <div style="margin-top:14px;">
          <a href="<?= $sonyLivCoverageUrl ?>" style="display:inline-block;background:#071d46;color:#ffffff;text-decoration:none;font-size:12px;letter-spacing:.6px;text-transform:uppercase;padding:11px 17px;border-radius:999px;">View Sony LIV Coverage</a>
        </div>
      </td>
    </tr>
  </table>
</td>
</tr>



<!-- PCL LEGACY -->
<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 Pro Corporate League</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;">15 Years Of Building Corporate Teams Beyond The Workplace</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;">15+</div><div style="font-size:11px;line-height:1.5;color:#eaf1ff;">Years Building Corporate Cricket</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;">500+</div><div style="font-size:11px;line-height:1.5;color:#eaf1ff;">Corporate Teams Engaged</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;">3000+</div><div style="font-size:11px;line-height:1.5;color:#eaf1ff;">Matches Conducted</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;">Sony LIV</div><div style="font-size:11px;line-height:1.5;color:#eaf1ff;">Finals Ecosystem</div></div></td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td style="padding:0 24px 24px 24px;font-size:13px;line-height:1.8;color:#dfe8ff;">
        Corporate culture, employee wellness, team bonding and employer branding — built through a structured corporate cricket ecosystem.
      </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;">Beyond the cricket field, participating organizations benefit through employee engagement initiatives, leadership visibility, employer-brand positioning and company-wide recognition opportunities.</p>
    <p style="margin:0 0 14px 0;">We would be honoured to welcome <?= $safeTeam ?> as part of the founding qualification round of the Corporate World Cup™.</p>
    <p style="margin:0 0 14px 0;">We look forward to hearing from you.</p>
    
    
    <!-- <p style="margin:18px 0 0 0;">Warm regards,<br><br>Sachin Gupta<br>Founder & CEO<br>Pro Corporate League®<br><br>Corporate World Cup™<br>A Pro Corporate League Initiative<br><br>
      📧 <a href="mailto:sachin.gupta@procorporateleague.com" style="color:#071d46;text-decoration:none;">sachin.gupta@procorporateleague.com</a><br>
      🌐 <a href="<?//= $cwcUrl ?>" style="color:#071d46;text-decoration:none;">corporateworldcup.com</a>
    </p> -->

    <p style="margin:18px 0 0 0;">
        Warm regards,<br><br>

        <strong>Sachin Gupta</strong><br>
        Founder &amp; CEO<br>
        <strong>Corporate World Cup™</strong><br><br>

        📧 <a href="mailto:sachin.gupta@corporateworldcup.com" style="color:#071d46;text-decoration:none;">
            sachin.gupta@corporateworldcup.com
        </a><br>
        🌐 <a href="<?= $cwcUrl ?>" style="color:#071d46;text-decoration:none;">
            corporateworldcup.com
        </a><br><br>

        <strong>A Pro Corporate League Initiative</strong><br>
        <strong>Pro Corporate League®</strong><br><br>

        📧 <a href="mailto:sachin.gupta@procorporateleague.com" style="color:#071d46;text-decoration:none;">
            sachin.gupta@procorporateleague.com
        </a><br>
        🌐 <a href="<?= $pclUrl ?>" style="color:#071d46;text-decoration:none;">
            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;">Begin The Corporate World Cup™ Qualification Journey</div>
  <div style="font-size:14px;line-height:1.7;color:#dfe8ff;margin-bottom:20px;">Review the detailed deliverables and reserve the <?= $safeSector ?> category for <?= $safeCity ?>.</div>
  <!-- <a href="<?= $teamDashboardUrl ?>" 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;">View Team Dashboard</a>
  <a href="<?= $reserveUrl ?>" 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;">Reserve Category</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/pcl/media/pcl-print-media-coverage-corporate-cricket-india/" style="color:#d6ad45;text-decoration:none;">Print Media</a> &nbsp;|&nbsp;
    <a href="https://www.procorporateleague.com/pcl/media/pcl-corporate-cricket-electronic-media-coverage/" style="color:#d6ad45;text-decoration:none;">Electronic Media</a><br>
    <a href="https://www.procorporateleague.com/ai/pcl-ai-sports-tech-platform/" style="color:#d6ad45;text-decoration:none;">PCL AI Sports Tech</a> &nbsp;|&nbsp;
    <a href="https://www.procorporateleague.com/ai/corporate-cricket-rankings-india" style="color:#d6ad45;text-decoration:none;">Corporate Cricket Rankings</a><br>
    pcl@procorporateleague.com<br>
    © 2026 Pro Corporate League. This communication is an official Corporate World Cup™ invitation for <?= $safeTeam ?>.
  </div>
</td>
</tr>

</table>
</td>
</tr>
</table>

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

/* ===============================
   SEND EMAIL
================================ */
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'sachin.gupta@procorporateleague.com';
    $mail->Password   = 'mwhqomapdbzzvjeb';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    $mail->setFrom('sachin.gupta@procorporateleague.com', 'Pro Corporate League');
    $mail->addAddress($postData['email'], $postData['name']);
    $mail->addCC('sachin.gupta@procorporateleague.com', 'Sachin Gupta');
    $mail->addCC('sachin.gupta@corporateworldcup.com', 'Sachin Gupta');
    $mail->addCC('info@corporateworldcup.com', 'Corporate World Cup Info');

    $mail->CharSet  = 'UTF-8';
    $mail->Encoding = 'base64';
    $mail->isHTML(true);
    $mail->Subject = ucwords($postData['team_name']).' 🏆 Registration Confirmed | Your Road to the Corporate World Cup™ Begins';
    $mail->Body    = $emailBody;

    $mail->send();


  



    // ✅ module_id / submodule_id hardcode kiya — backend 'module_id cannot be null' error fix
    $enterpriseTrackResult = pcl_email_enterprise_track($mail, 'sent', [
      'module_id' => 10,
        'submodule_id' => 10,
       'module_key' => 'lead_management',
        'submodule_key' => 'lead_management',
    ]);

    $trackingResult = pcl_email_log_dynamic($mail, $emailBody ?? '', $postData ?? [], [
        'status' => 'sent',
        'delivery_status' => 'sent',
        'message' => 'Email sent successfully',
        'module_id' => 10,
        'submodule_id' => 10,
        'module_key' => 'lead_management',
        'submodule_key' => 'lead_management',
    ]);

    pcl_write_error_log('email_sent_success', [
        'to' => $postData['email'],
        'lead_id' => $leadId,
        'tracking' => $trackingResult,
        'enterprise_tracking' => $enterpriseTrackResult
    ]);

    $tracking = pcl_track_email_if_available($mail, [
        'lead_id' => $leadId,
        'mobile' => $postData['mobile'],
        'recipient_email' => $postData['email'],
        'recipient_name' => $postData['name'],
        'subject' => $subject,
        'module_id' => 10,
        'submodule_id' => 10,
        'module_key' => 'lead_management',
        'submodule_key' => 'lead_management',
        'active_file_name' => basename(__FILE__),
        'calling_file_url' => $_SERVER['HTTP_REFERER'] ?? '',
        'full_email_html' => $emailBody
    ]);



   

     // whatsappp msg
    include('whatsapp/constant.php');

    // Meta WhatsApp Cloud API configuration
    $accessToken   = ACCESS_TOKEN;
    $phoneNumberId = PHONE_NUMBER_ID;

    // Replace this with the exact approved template name shown in Meta.
    $templateName = 'registration_confirmation';

    // Example usage values
    $recipientMobile    = $postData['mobile']; // WhatsApp recipient
    $playerName         = $postData['name'];   // {{1}} body - naam
    $referenceId        = $postData['reference_id'];    // {{2}} body - registration id
    $registeredMobile   = $postData['mobile'];
    // ✅ kept as-is for display/labeling elsewhere — NOT used for the WhatsApp
    // 'recipient_type' field anymore (Meta only accepts individual/group/null there).
    $registrationType   = 'Team';

    // Keep digits only and include country code.
    $whatsappNumber = preg_replace('/\D+/', '', (string)$recipientMobile);
    if (strlen($whatsappNumber) === 10) {
        $whatsappNumber = '91' . $whatsappNumber;
    }

    // ✅ FIX — Meta 400s with "The parameter to is required" jab $whatsappNumber empty hota hai.
    // Isko explicitly catch karke Meta ko empty request bhejne se pehle hi rok rahe hain.
    if (empty($whatsappNumber) || strlen($whatsappNumber) < 10) {
        pcl_write_error_log('whatsapp_skipped_invalid_number', [
            'raw_mobile' => $recipientMobile,
            'postData_mobile' => $postData['mobile'] ?? null,
            'requestData_mobile' => $requestData['mobile'] ?? null,
        ]);

        $result = [
            'success' => false,
            'error'   => 'WhatsApp not sent: mobile number missing or invalid (received: "' . $recipientMobile . '")'
        ];

        header('Content-Type: application/json');
        echo json_encode($result, JSON_PRETTY_PRINT);

        echo json_encode([
            "status_code" => 200,
            "status"      => "success",
            "message"     => "Registration email sent successfully",
            "tracking"    => $trackingResult,
            "enterprise_tracking" => $enterpriseTrackResult,
            "whatsapp"    => $result
        ]);
        exit;
    }

  

    // Registration details link
    $dashboardUrl = 'https://www.procorporateleague.com/pcl/corporate-world-cup/team-registration/pcl-team-dashboard.php'
        . '?lead_id=' . urlencode($referenceId)
        . '&mobile=' . urlencode($registeredMobile);

    // Button URL field "https://{{1}}" hai to bina https:// ke value jaani chahiye
    $buttonDynamicValue = preg_replace('#^https://#', '', $dashboardUrl);

    $whatsappTextParams = [
        'playerName' => $playerName,
        'referenceId' => $referenceId,
        'dashboardUrl' => $dashboardUrl,
        'buttonDynamicValue' => $buttonDynamicValue,
    ];
    $emptyParams = [];
    foreach ($whatsappTextParams as $key => $val) {
        if ($val === null || trim((string)$val) === '') {
            $emptyParams[] = $key;
        }
    }
    if (!empty($emptyParams)) {
        pcl_write_error_log('whatsapp_empty_template_param', [
            'empty_params' => $emptyParams,
            'playerName' => $playerName,
            'referenceId' => $referenceId,
            'dashboardUrl' => $dashboardUrl,
            'buttonDynamicValue' => $buttonDynamicValue,
            'raw_name' => $postData['name'] ?? null,
            'raw_reference_id' => $postData['reference_id'] ?? null,
        ]);
    }

    // Safe fallbacks — Meta ko kabhi bhi empty text value nahi jaani chahiye
    $playerName         = (trim((string)$playerName) !== '') ? $playerName : 'Participant';
    $referenceId        = (trim((string)$referenceId) !== '') ? $referenceId : 'NA';
    $buttonDynamicValue = (trim((string)$buttonDynamicValue) !== '') ? $buttonDynamicValue : preg_replace('#^https://#', '', 'https://www.procorporateleague.com/pcl/corporate-world-cup/team-registration/pcl-team-dashboard.php');

    $payload = [
        'messaging_product' => 'whatsapp',
        'recipient_type'    => 'individual',
        'to'                => $whatsappNumber,
        'type'              => 'template',
        'template'          => [
            'name'     => $templateName,
            'language' => [
                'code' => 'en'
            ],
            'components' => [
                [
                    'type'       => 'body',
                    'parameters' => [
                        ['type' => 'text', 'text' => $playerName],   // {{1}}
                        ['type' => 'text', 'text' => $referenceId],  // {{2}}
                        ['type' => 'text', 'text' => $dashboardUrl]  // {{3}}
                    ]
                ],
                [
                    'type'       => 'button',
                    'sub_type'   => 'url',
                    'index'      => '0',
                    'parameters' => [
                        ['type' => 'text', 'text' => $buttonDynamicValue]
                    ]
                ]
            ]
        ]
    ];

    $apiUrl = APP_URL . $phoneNumberId . '/messages';

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL            => $apiUrl,
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS     => json_encode(
            $payload,
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        )
    ]);

    $response  = curl_exec($curl);
    $httpCode  = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $curlError = curl_error($curl);
    curl_close($curl);

    if ($response === false || $curlError !== '') {
        $result = [
            'success' => false,
            'error'   => $curlError ?: 'WhatsApp API request failed'
        ];
    } else {
        $result = [
            'success'   => $httpCode >= 200 && $httpCode < 300,
            'http_code' => $httpCode,
            'response'  => json_decode($response, true)
        ];
    }

    // ✅ Log WhatsApp result too so failures are visible in the same error log as email
    pcl_write_error_log('whatsapp_send_result', [
        'to' => $whatsappNumber,
        'lead_id' => $leadId,
        'result' => $result
    ]);

    header('Content-Type: application/json');
    echo json_encode($result, JSON_PRETTY_PRINT);
    // end whatsapp msg

    // ✅ SINGLE echo
    echo json_encode([
        "status_code" => 200,
        "status"      => "success",
        "message"     => "Registration email sent successfully",
        "tracking"    => $trackingResult,
        "enterprise_tracking" => $enterpriseTrackResult,
        "whatsapp"    => $result
    ]);
    exit;

} catch (Exception $e) {

    $errorMsg = !empty($mail->ErrorInfo) ? $mail->ErrorInfo : $e->getMessage();

    pcl_write_error_log('email_send_failed', [
        'to' => $postData['email'] ?? null,
        'lead_id' => $leadId,
        'error' => $errorMsg,
        'exception' => $e->getMessage()
    ]);

    // ✅ module_id / submodule_id hardcode kiya — yahan bhi
    pcl_email_enterprise_track($mail, 'failed', array(
        'error_message' => $errorMsg,
        'module_id' => 10,
        'submodule_id' => 10,
        'module_key' => 'lead_management',
        'submodule_key' => 'lead_management',
    ));

    $trackingResult = pcl_email_log_dynamic($mail, $emailBody ?? '', $postData ?? [], [
        'status' => 'failed',
        'delivery_status' => 'failed',
        'message' => $errorMsg,
        'error_message' => $errorMsg,
        'module_id' => 10,
        'submodule_id' => 10,
        'module_key' => 'lead_management',
        'submodule_key' => 'lead_management',
    ]);

    pcl_write_error_log('tracking_after_failure', ['tracking_result' => $trackingResult]);

    echo json_encode([
        "status_code" => 500,
        "status"      => "error",
        "message"     => $errorMsg,
        "tracking"    => $trackingResult
    ]);
    exit;
}
?>
