<?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");

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

$requestData = json_decode(file_get_contents("php://input"), true);

$ccList = $requestData['cc'] ?? [];

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

/* ── TEAM ID ── */
$teamIdParam = $_GET['team_id'] ?? $_POST['team_id'] ?? $requestData['team_id'] ?? 2009;
$teamIdParam = (int)$teamIdParam;
if ($teamIdParam <= 0) $teamIdParam = 2009;

$email = $_GET['email'] ?? $_POST['email'] ?? $requestData['email'] ?? '';
$toName = $_GET['to_name'] ?? $_POST['to_name'] ?? $requestData['to_name'] ?? '';

/* ── FETCH AI-360 ── */
$ai360curl = curl_init();
curl_setopt_array($ai360curl, [
    CURLOPT_URL            => 'https://procorporateleague.com/pcl_rest/api/v12/teams/' . $teamIdParam . '/ai-360',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => '',
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => 'GET',
]);
$ai360response = curl_exec($ai360curl);
curl_close($ai360curl);

$getData = json_decode($ai360response, true);

$team    = $getData['data']['team']           ?? [];
$stats   = $getData['data']['stats']          ?? [];
$ranking = $getData['data']['ranking']        ?? [];
$players = $getData['data']['players']        ?? [];
$topPerf = $getData['data']['top_performers'] ?? [];

$teamName     = $team['team_name'] ?? 'N/A';
$teamId       = $team['team_id']   ?? $teamIdParam;
$teamRank     = $ranking['rank_no'] ?? ($stats['rank_no'] ?? ($team['current_rank'] ?? 'N/A'));
$playersCount = count($players) > 0 ? count($players) : 'N/A';
$teamLogoUrl  = 'https://procorporateleague.com/wp-includes/images/team/' . $teamIdParam . '.png';

$winPct        = (float)($team['win_percentage']   ?? 0);
$battingAiRaw  = (float)($team['batting_ai_score'] ?? 0);
$bowlingAiRaw  = (float)($team['bowling_ai_score'] ?? 0);
$fieldingAiRaw = (float)($team['fielding_ai_score'] ?? 0);

$overallRating       = number_format($winPct, 2);
$selectionConfidence = $winPct;
$selectionBand       = $winPct >= 70 ? 'Selected - PCL Season 12 Review'
                     : ($winPct >= 50 ? 'Under Review - PCL Season 12'
                     : 'Evaluation Stage - PCL Season 12');

$badge1 = 'Corporate Team';
$badge2 = $winPct >= 70 ? 'Elite' : ($winPct >= 50 ? 'Strong' : 'Developing');
$badge3 = 'Season ' . ($team['seasons_played'] ?? '12');

$aiReadiness = round($winPct);

$totalMatches = $team['matches_played']     ?? 'N/A';
$totalWins    = $team['matches_won']        ?? 'N/A';
$winRate      = $team['win_percentage']     ?? 'N/A';
$runRate      = $team['avg_runs_per_match'] ?? 'N/A';
$totalRuns    = $team['total_runs_scored']  ?? 'N/A';

$consistencyScore = ($totalMatches !== 'N/A' && $totalWins !== 'N/A' && (float)$totalMatches > 0)
    ? (int)min(100, round(((float)$totalWins / (float)$totalMatches) * 100)) : 0;
$battingScore  = (int)min(100, round((float)$battingAiRaw  / 30));
$bowlingScore  = (int)min(100, round((float)$bowlingAiRaw  / 30));
$fieldingScore = (int)min(100, round((float)$fieldingAiRaw / 5));
$balanceScore  = (int)min(100, round(((float)$battingScore + (float)$bowlingScore) / 2));
$momentumScore = (int)min(100, round((float)$winPct));

$playersSorted = $players;
usort($playersSorted, fn($a, $b) => (float)($b['overall_ai_score'] ?? 0) <=> (float)($a['overall_ai_score'] ?? 0));
$captainName = !empty($playersSorted[0]['player_name']) ? $playersSorted[0]['player_name'] : 'N/A';

$aiAnalystNote = $teamName . ' profiles as a live corporate cricket contender with mapped player depth, '
    . 'usable PCL match-form signals and a strong overall participation footprint. '
    . 'Strong corporate team profile with proven match sample, winning conversion and squad depth for PCL Season 12 review.';

$winRateDisplay = ($winRate !== 'N/A' && strpos((string)$winRate, '%') === false)
    ? $winRate . '%' : $winRate;

$meterPct = min(100, max(0, (float)$selectionConfidence));

$overallAiScore = (float)($team['overall_ai_score'] ?? 0)
    + (float)$battingAiRaw + (float)$bowlingAiRaw + (float)$fieldingAiRaw;

$rankNum   = (int)$teamRank;
$score     = (int)$aiReadiness;
$ringColor = $score >= 70 ? '#16a34a' : ($score >= 50 ? '#f59e0b' : '#dc2626');

/* ── HELPER FUNCTIONS ── */
function getPlayerRuns(array $p): string {
    return (string)($p['runs'] ?? $p['runs_scored'] ?? $p['total_runs'] ?? $p['career_runs'] ?? '');
}
function getPlayerWickets(array $p): string {
    return (string)($p['wickets'] ?? $p['wickets_taken'] ?? $p['total_wickets'] ?? $p['career_wickets'] ?? '');
}
function getPlayerStats(array $p): string {
    return (string)($p['stats'] ?? $p['performance'] ?? $p['stat_line'] ?? '');
}
function getPlayerRank(array $p): string {
    return (string)($p['pcl_rank'] ?? $p['rank'] ?? $p['hall_of_fame_rank'] ?? $p['overall_rank'] ?? $p['hof_rank'] ?? '');
}
function getPlayerImage(array $p): string {
    return (string)($p['player_image'] ?? $p['image'] ?? $p['photo'] ?? $p['profile_image'] ?? $p['avatar'] ?? '');
}

/* ── HALL OF FAME ── */
if (!function_exists('pclFetchJson')) {
    function pclFetchJson(string $url): array {
        $ch = curl_init();
        curl_setopt_array($ch, [CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_USERAGENT => 'PCL-AI-Email-V12']);
        $r = curl_exec($ch); curl_close($ch);
        $j = json_decode((string)$r, true);
        return is_array($j) ? $j : [];
    }
}
if (!function_exists('pclRowsFromApi')) {
    function pclRowsFromApi(array $json): array {
        if (isset($json['data']) && is_array($json['data'])) return $json['data'];
        if (isset($json['results']) && is_array($json['results'])) return $json['results'];
        if (isset($json[0]) && is_array($json[0])) return $json;
        return [];
    }
}
if (!function_exists('pclNormName')) {
    function pclNormName(string $name): string {
        $name = strtolower(trim($name));
        $name = preg_replace('/[^a-z0-9]+/', ' ', $name);
        return trim(preg_replace('/\s+/', ' ', $name));
    }
}

$axaPlayerById = [];
$axaPlayerByName = [];
foreach (array_merge($players ?: [], $topPerf ?: [], $playersSorted ?: []) as $pRow) {
    if (!is_array($pRow)) continue;
    $pid = (int)($pRow['player_id'] ?? $pRow['id'] ?? 0);
    $pname = (string)($pRow['player_name'] ?? $pRow['name'] ?? '');
    if ($pid > 0) $axaPlayerById[$pid] = $pRow;
    if ($pname !== '') $axaPlayerByName[pclNormName($pname)] = $pRow;
}

$hallApis = [
    'players'     => 'https://procorporateleague.com/pcl_rest/api/v12/rankings/players/all-time?limit=500&v=8',
    'batsmen'     => 'https://procorporateleague.com/pcl_rest/api/v12/rankings/batsmen/all-time?limit=500&v=8',
    'bowlers'     => 'https://procorporateleague.com/pcl_rest/api/v12/rankings/bowlers/all-time?limit=500&v=8',
    'allrounders' => 'https://procorporateleague.com/pcl_rest/api/v12/rankings/all-rounders/all-time?limit=500&v=8',
    'fielders'    => 'https://procorporateleague.com/pcl_rest/api/v12/rankings/fielders/all-time?limit=500&v=8',
];

$hallOfFamePlayers = [];
foreach ($hallApis as $category => $apiUrl) {
    $rows = pclRowsFromApi(pclFetchJson($apiUrl));
    foreach ($rows as $row) {
        if (!is_array($row)) continue;
        $pid   = (int)($row['player_id'] ?? $row['id'] ?? 0);
        $pname = (string)($row['player_name'] ?? $row['name'] ?? '');
        $norm  = pclNormName($pname);
        $isAxaPlayer = false; $teamPlayer = [];
        if ($pid > 0 && isset($axaPlayerById[$pid])) { $isAxaPlayer = true; $teamPlayer = $axaPlayerById[$pid]; }
        elseif ($norm !== '' && isset($axaPlayerByName[$norm])) { $isAxaPlayer = true; $teamPlayer = $axaPlayerByName[$norm]; }
        if (!$isAxaPlayer) continue;
        $rank = (int)($row['rank_no'] ?? $row['rank'] ?? $row['pcl_rank'] ?? 9999);
        if ($rank <= 0 || $rank > 100) continue;
        $key   = $pid > 0 ? 'id_' . $pid : 'name_' . $norm;
        $runs  = (int)($row['total_runs'] ?? $row['runs'] ?? $teamPlayer['total_runs'] ?? $teamPlayer['runs'] ?? 0);
        $wkts  = (int)($row['total_wickets'] ?? $row['wickets'] ?? $teamPlayer['total_wickets'] ?? $teamPlayer['wickets'] ?? 0);
        $image = (string)($row['profile_image'] ?? $row['player_image'] ?? $row['image'] ?? getPlayerImage($teamPlayer));
        $candidate = [
            'player_id' => $pid, 'player_name' => $pname ?: (string)($teamPlayer['player_name'] ?? 'Player'),
            'pcl_rank' => $rank, 'rank' => $rank, 'profile_image' => $image, 'player_image' => $image,
            'total_runs' => $runs, 'runs' => $runs, 'total_wickets' => $wkts, 'wickets' => $wkts,
            'stats' => trim(($runs > 0 ? $runs . ' Runs' : '') . (($runs > 0 && $wkts > 0) ? ' / ' : '') . ($wkts > 0 ? $wkts . ' Wkts' : '')),
            'hof_category' => $category,
        ];
        if (!isset($hallOfFamePlayers[$key]) || $rank < (int)$hallOfFamePlayers[$key]['pcl_rank'])
            $hallOfFamePlayers[$key] = $candidate;
    }
}
usort($hallOfFamePlayers, fn($a, $b) => ((int)($a['pcl_rank'] ?? 9999)) <=> ((int)($b['pcl_rank'] ?? 9999)));

if (empty($hallOfFamePlayers) && (int)$teamIdParam === 2009) {
    $hallOfFamePlayers = [
        ['player_name'=>'Parminder Singh','pcl_rank'=>7,'rank'=>7,'total_runs'=>374,'runs'=>374,'total_wickets'=>45,'wickets'=>45,'stats'=>'374 Runs / 45 Wkts','profile_image'=>''],
        ['player_name'=>'Aditya Dubey','pcl_rank'=>20,'rank'=>20,'total_runs'=>535,'runs'=>535,'total_wickets'=>0,'wickets'=>0,'stats'=>'535 Runs','profile_image'=>''],
        ['player_name'=>'Badrish Naithani','pcl_rank'=>29,'rank'=>29,'total_runs'=>483,'runs'=>483,'total_wickets'=>0,'wickets'=>0,'stats'=>'483 Runs','profile_image'=>''],
        ['player_name'=>'Pulkit Bhagat','pcl_rank'=>29,'rank'=>29,'total_runs'=>42,'runs'=>42,'total_wickets'=>28,'wickets'=>28,'stats'=>'42 Runs / 28 Wkts','profile_image'=>''],
        ['player_name'=>'Amit Naithani','pcl_rank'=>43,'rank'=>43,'total_runs'=>88,'runs'=>88,'total_wickets'=>25,'wickets'=>25,'stats'=>'88 Runs / 25 Wkts','profile_image'=>''],
    ];
}
if (!empty($hallOfFamePlayers)) $topPerf = array_values(array_slice($hallOfFamePlayers, 0, 5));

/* ── 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,
];

/* ── CRIC HEROES ── */
if (!function_exists('safe_json')) { function safe_json($v,$d=[]) { if(is_array($v))return $v; if(!is_string($v)||trim($v)==='')return $d; $j=json_decode($v,true); return is_array($j)?$j:$d; } }
if (!function_exists('pick')) { function pick($a,$keys,$d='') { if(!is_array($a))return $d; foreach((array)$keys as $k) { if(isset($a[$k])&&$a[$k]!==''&&$a[$k]!==null)return $a[$k]; } return $d; } }
if (!function_exists('n')) { function n($v,$d=0) { $v=str_replace([',','%'],'',(string)$v); return is_numeric($v)?$v+0:$d; } }
if (!function_exists('arr_values_from_report')) { function arr_values_from_report($x,$metric='value') { $out=[]; if(!is_array($x))return $out; foreach($x as $r) { if(is_array($r)) { $name=trim((string)($r['name']??$r['player_name']??$r['full_name']??'Player')); $val=n($r[$metric]??$r['value']??$r['runs']??$r['wickets']??$r['dismissals']??$r['score']??0,0); $out[]=[$name,$val,$r]; } elseif(is_string($r)) { $out[]=[trim($r),0,[]]; } } return $out; } }

$aiCh = curl_init();
curl_setopt_array($aiCh, [CURLOPT_URL => 'https://procorporateleague.com/pcl_rest/api/v9/lead/getAIReportCard/' . $teamIdParam,
    CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 8, CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => 'PCL-Team-AI', CURLOPT_HTTPHEADER => ['Accept: application/json']]);
$aiRaw = curl_exec($aiCh);
curl_close($aiCh);
$aiPayload = json_decode((string)$aiRaw, true);
if (!is_array($aiPayload)) $aiPayload = [];

if (!function_exists('email_list_rows')) { function email_list_rows($p) { if(!is_array($p))return []; if(array_keys($p)===range(0,count($p)-1))return $p; foreach(['data','result','results','records','rows','matches','list','response','players'] as $k) { if(isset($p[$k])&&is_array($p[$k])) { $x=$p[$k]; if(array_keys($x)===range(0,count($x)-1))return $x; } } return []; } }
if (!function_exists('email_rec')) { function email_rec($p) { if(!is_array($p))return []; if(array_keys($p)===range(0,count($p)-1))return $p[0]??[]; foreach(['data','result','record','details','response','match'] as $k) { if(isset($p[$k])&&is_array($p[$k])) return (array_keys($p[$k])===range(0,count($p[$k])-1))?($p[$k][0]??[]):$p[$k]; } return $p; } }

$aiRows = email_list_rows($aiPayload);
$aiRow  = $aiRows[0] ?? email_rec($aiPayload);
if (!is_array($aiRow)) $aiRow = [];

$ui              = safe_json(pick($aiRow, ['raw_ui_json','ui_ready_json','ui_json'], []), []);
$cricProfile     = $ui['cric_heroes_profile'] ?? [];
$boardSummary    = $ui['corporate_board_summary'] ?? [];
$externalSummary = $boardSummary['external_matches_summary'] ?? ($cricProfile['last_played_snapshot'] ?? []);
$teamCard        = $ui['team_card'] ?? [];

$cric = [
    'matches'  => n(pick($externalSummary, ['matches','total_matches'], pick($teamCard, ['external_matches','matches'], 0))),
    'wins'     => n(pick($externalSummary, ['won','wins','matches_won'], 0)),
    'lost'     => n(pick($externalSummary, ['lost','losses'], 0)),
    'win_rate' => n(pick($externalSummary, ['win_rate','winning_rate'], 0)),
    'members'  => n(pick($externalSummary, ['members','squad_members','players_mapped'], pick($teamCard, ['players_mapped'], 0))),
    'batting'  => arr_values_from_report($cricProfile['batting_core']  ?? ($ui['batting_leaderboard']  ?? []), 'runs'),
    'bowling'  => arr_values_from_report($cricProfile['bowling_core']  ?? ($ui['bowling_leaderboard']  ?? []), 'wickets'),
    'fielding' => arr_values_from_report($cricProfile['fielding_core'] ?? ($ui['fielding_leaderboard'] ?? []), 'dismissals'),
];
if (!$cric['members']) {
    $memberNames = [];
    foreach (array_merge($cric['batting'], $cric['bowling'], $cric['fielding']) as $cp)
        if (!empty($cp[0])) $memberNames[strtolower($cp[0])] = true;
    $cric['members'] = count($memberNames);
}
if ($cric['win_rate'] <= 0 && $cric['matches'] > 0 && $cric['wins'] > 0)
    $cric['win_rate'] = round(($cric['wins'] / $cric['matches']) * 100, 1);

$ch_matches  = $cric['matches'];
$ch_wins     = $cric['wins'];
$ch_lost     = $cric['lost'];
$ch_win_rate = $cric['win_rate'];
$ch_members  = $cric['members'];
$ch_batting  = $cric['batting'];
$ch_bowling  = $cric['bowling'];
$ch_fielding = $cric['fielding'];
$ch_win_rate_display = $ch_win_rate > 0 ? number_format($ch_win_rate, 1) . '%' : ($ch_matches > 0 ? '0%' : 'N/A');

$pcl_matches  = $team['matches_played']      ?? $totalMatches ?? 'N/A';
$pcl_wins     = $team['matches_won']         ?? $totalWins    ?? 'N/A';
$pcl_win_rate = $team['win_percentage']      ?? $winRate      ?? 'N/A';
$pcl_runs     = $team['total_runs_scored']   ?? $totalRuns    ?? 'N/A';
$pcl_wickets  = $team['total_wickets_taken'] ?? $getData['data']['stats']['total_wickets'] ?? 'N/A';
$pcl_run_rate = $team['avg_runs_per_match']  ?? $runRate      ?? 'N/A';
$pcl_win_rate_display = ($pcl_win_rate !== 'N/A' && strpos((string)$pcl_win_rate, '%') === false)
    ? number_format((float)$pcl_win_rate, 2) . '%' : $pcl_win_rate;

/* ── GRADE ── */
if (!function_exists('getGrade')) {
    function getGrade(int $score): string {
        if ($score >= 90) return 'A+'; if ($score >= 80) return 'A'; if ($score >= 70) return 'A-';
        if ($score >= 60) return 'B+'; if ($score >= 50) return 'B'; if ($score >= 40) return 'C+';
        return 'C';
    }
}
$readiness       = (int)($aiReadiness ?? $score ?? 75);
$overallGrade    = getGrade($score ?? 75);
$battingGrade    = getGrade($battingScore ?? 70);
$bowlingGrade    = getGrade($bowlingScore ?? 70);
$headlineBadge   = 'PREMIUM CORPORATE TEAM';
$aiRecommendation = pick($finalReport ?? [], ['recommendation','summary','verdict'], $aiAnalystNote ?? '');
$strengths = [];

$year = date('Y');
$topBadgeEmoji = ['1' => '&#128293;', '2' => '&#129351;', '3' => '&#11088;'];


/* ===============================
   PLAYER IMAGE URL FUNCTION
================================ */
function getPlayerImageUrl($teamId, $player)
{
    $pid = (int)($player['player_id'] ?? $player['id'] ?? 0);

    // Default Avatar
    $name = trim($player['player_name'] ?? $player['name'] ?? 'Player');

    $defaultAvatar = "https://ui-avatars.com/api/?name="
        . rawurlencode($name)
        . "&background=0B2C6B&color=fff&bold=true&size=200";

    // If no player id
    if ($pid <= 0) {
        return $defaultAvatar;
    }

    // Official image URL
    $imageUrl = "https://procorporateleague.com/wp-includes/images/pcl/Player%20Gallery/"
        . rawurlencode((string)$teamId)
        . "/"
        . rawurlencode((string)$pid)
        . ".png";

    // Check image exists
    $headers = @get_headers($imageUrl);

    if (
        $headers &&
        strpos($headers[0], '200') !== false
    ) {
        return $imageUrl;
    }

    // Fallback avatar
    return $defaultAvatar;
}


/* ===============================
   INITIALS FUNCTION
================================ */
if (!function_exists('pclInitials'))
{
    function pclInitials(string $name): string
    {
        $parts = preg_split('/\s+/', trim($name));

        $a = strtoupper(substr($parts[0] ?? 'P', 0, 1));
        $b = strtoupper(substr($parts[1] ?? ($parts[0] ?? 'L'), 0, 1));

        return $a . $b;
    }
}


/* ===============================
   DB: SMTP CREDENTIALS
================================ */
$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"]);
    die;
}

ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PCL AI Report - <?= htmlspecialchars($teamName) ?></title>
<!--[if mso]>
<style>
  table { border-collapse: collapse; }
  .mso-hide { display: none; }
</style>
<![endif]-->
</head>
<body style="margin:0;padding:0;background-color:#e8edf5;font-family:Georgia,'Times New Roman',serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;">

<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#e8edf5;">
<tr>
<td align="center" style="padding:24px 12px;">

<!--[if (gte mso 9)|(IE)]>
<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="640"><tr><td>
<![endif]-->

<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="720" style="max-width:720px;background-color:#ffffff;border-radius:0;overflow:hidden;">

  <!-- ══════════════════════════════════════════HEADER: PCL NAVY + GOLD══════════════════════════════════════════ -->
  <tr>
    <td style="background-color:#0b2c6b;padding:0;">

      <!-- TOP NAV BAR -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td style="padding:16px 28px;border-bottom:1px solid rgba(255,255,255,0.08);">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <td valign="middle">
                  <table role="presentation" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                     <td valign="middle" style="padding-right:12px;">
                        <table cellpadding="0" cellspacing="0" border="0">
                          <tr>
                            <td align="center" valign="middle"
                              style="
                                width:46px;
                                height:46px;
                                background:#0d2a5e;
                                border-radius:10px;
                                border:1px solid rgba(215,175,89,0.3);
                              ">

                              <img 
                                src="https://www.procorporateleague.com/2026/pcl/Imp_PCL_Logo_Black.png"
                                width="48"
                                style="display:block;border:0;height:auto;"
                                alt="PCL">

                            </td>
                          </tr>
                        </table>
                      </td>
                      <td valign="middle">
                        <div style="font-family:Georgia,'Times New Roman',serif;font-size:15px;font-weight:700;color:#d7af59;letter-spacing:0.5px;line-height:1.2;">Pro Corporate League</div>
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:10px;color:#fff;letter-spacing:1px;text-transform:uppercase;margin-top:2px;">Corporate Cricket AI Intelligence</div>
                      </td>
                    </tr>
                  </table>
                </td>
                <td align="right" valign="middle">
                  <div style="display:inline-block;border:1px solid rgba(215,175,89,0.4);color:#d7af59;font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:700;padding:7px 16px;border-radius:2px;letter-spacing:0.5px;">#CorporateKaWorldCup</div>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>

      <!-- GOLD DIVIDER LINE -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr><td style="height:3px;background:linear-gradient(90deg,#d7af59 0%,#f5e4a0 50%,#d7af59 100%);font-size:0;line-height:0;">&nbsp;</td></tr>
      </table>

      <!-- HERO SECTION -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <!-- LEFT: Team Info -->
          <td valign="middle" width="50%" style="padding:32px 0 32px 28px;">
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:9px;font-weight:700;color:#d7af59;letter-spacing:2px;text-transform:uppercase;margin-bottom:14px;">&#9654; Invitational Roadmap 2026</div>
            <div style="font-family:Georgia,'Times New Roman',serif;font-size:36px;color:#fff;margin-bottom:8px;font-style:italic;">Congratulations,</div>
            <div style="font-family:Georgia,'Times New Roman',serif;font-size:30px;font-weight:700;color:#ffffff;line-height:1.15;margin-bottom:6px;"><?= htmlspecialchars($teamName) ?></div>
            <div style="height:3px;width:50px;background-color:#d7af59;margin:12px 0 16px;"></div>
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#fff;line-height:1.8;">
              Shortlisted from <strong style="color:#d7af59;">200+ corporate teams</strong><br>
              across Delhi &bull; NCR &bull; Gurgaon &bull; Noida
            </div>
          </td>

          <!-- RIGHT: Team Stats Card -->
          <td valign="middle" width="50%" style="padding:24px 24px 24px 16px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#071a3e;border:1px solid rgba(215,175,89,0.25);">
              <tr>
                <td style="padding:18px 18px 0;">
                  <table role="presentation" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                      <td valign="middle" style="padding-right:14px;">
                        <div style="width:60px;height:60px;background-color:#ffffff;border:2px solid #d7af59;overflow:hidden;">
                          <img src="<?= htmlspecialchars($teamLogoUrl) ?>" width="60" height="60" alt="<?= htmlspecialchars($teamName) ?>" style="display:block;border:0;object-fit:contain;">
                        </div>
                      </td>
                      <td valign="middle">
                        <div style="font-family:Georgia,'Times New Roman',serif;font-size:42px;font-weight:700;color:#d7af59;line-height:1;">#<?= htmlspecialchars((string)$teamRank) ?></div>
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:9px;color:#fff;text-transform:uppercase;letter-spacing:1px;margin-top:4px;">PCL All-Time AI Rank</div>
                      </td>
                    </tr>
                  </table>
                </td>
              </tr>
              <tr>
                <td style="padding:0;">
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-top:1px solid rgba(255,255,255,0.07);margin-top:14px;">
                    <tr>
                      <td align="center" style="padding:12px 4px;border-right:1px solid rgba(255,255,255,0.07);">
                        <div style="font-family:Georgia,'Times New Roman',serif;font-size:17px;font-weight:700;color:#ffffff;line-height:1;"><?= number_format($overallAiScore) ?></div>
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:8px;color:#fff;text-transform:uppercase;letter-spacing:0.8px;margin-top:4px;">AI Score</div>
                      </td>
                      <td align="center" style="padding:12px 4px;border-right:1px solid rgba(255,255,255,0.07);">
                        <div style="font-family:Georgia,'Times New Roman',serif;font-size:17px;font-weight:700;color:#ffffff;line-height:1;"><?= htmlspecialchars((string)($team['season_start_year'] ?? $team['first_season'] ?? date('Y'))) ?></div>
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:8px;color:#fff;text-transform:uppercase;letter-spacing:0.8px;margin-top:4px;">Since</div>
                      </td>
                      <td align="center" style="padding:12px 4px;border-right:1px solid rgba(255,255,255,0.07);">
                        <div style="font-family:Georgia,'Times New Roman',serif;font-size:17px;font-weight:700;color:#ffffff;line-height:1;"><?= htmlspecialchars((string)$totalMatches) ?></div>
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:8px;color:#fff;text-transform:uppercase;letter-spacing:0.8px;margin-top:4px;">Matches</div>
                      </td>
                      <td align="center" style="padding:12px 4px;">
                        <div style="font-family:Georgia,'Times New Roman',serif;font-size:17px;font-weight:700;color:#d7af59;line-height:1;"><?= htmlspecialchars((string)$winRateDisplay) ?></div>
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:8px;color:#fff;text-transform:uppercase;letter-spacing:0.8px;margin-top:4px;">Win %</div>
                      </td>
                    </tr>
                  </table>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>

      <!-- BOTTOM GOLD LINE -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr><td style="height:3px;background:linear-gradient(90deg,#d7af59 0%,#f5e4a0 50%,#d7af59 100%);font-size:0;line-height:0;">&nbsp;</td></tr>
      </table>

    </td>
  </tr>
  <!-- ══ END HEADER ══ -->

  
  <!-- ══════════════════════════════════════════SELECTION MESSAGE══════════════════════════════════════════ -->
  <tr>
    <td style="padding:32px 28px 0;">
      <p style="margin:0 0 14px;font-family:Georgia,'Times New Roman',serif;font-size:20px;font-weight:700;color:#04122b;line-height:1.3;">
        Team <?= htmlspecialchars($teamName);?>,
      </p>
      <p style="margin:0 0 16px;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.9;color:#2c3e5a;">
        This isn’t just an update —
        this is your official entry into #CorporateKaWorldCup.
      </p>
      <p style="margin:0 0 24px;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.9;color:#2c3e5a;">
        Welcome to India’s Largest Corporate Cricket Ecosystem, where serious corporate team compete, perform, and get recognised. Your performance has been evaluated through PCL AI and advanced into the next stage of the selection pathway.
      </p>
      <p style="margin:0 0 24px;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.9;color:#2c3e5a;">
        PCL is not an open-entry tournament. <br>
        Only selected corporate teams with verified competitive performance, organizational participation, and long-term cricket ecosystem presence are invited into the qualification process.
      </p>
      <p>
        <strong>Why <?= htmlspecialchars($teamName);?> Was Shortlisted</strong>
        <ul class="shortlist-points">
            <li>Strong corporate participation continuity</li>
            <li>High match conversion ratio</li>
            <li>Verified player ecosystem depth</li>
            <li>Consistent NCR competitive presence</li>
            <li>Proven team retention &amp; stability</li>
            <li>Positive PCL AI confidence indicators</li>
        </ul>
      </p>

      <!-- <p>
        <strong>Next Qualification Steps</strong>
        <ul class="qualification-steps">
            <li>Qualification slot reservation</li>
            <li>Team verification &amp; management onboarding</li>
            <li>PCL Season 12 corporate allocation</li>
            <li>Challenger qualification mapping</li>
            <li>#CorporateKaWorldCup pathway activation</li>
        </ul>
      </p> -->
    </td>
  </tr>
  <!-- ══ END SELECTION ══ -->


  <!-- ══════════════════════════════════════════PCL AI RATING CARD══════════════════════════════════════════ -->
  <tr>
    <td style="padding:24px 28px 0;">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" 
            style="background: linear-gradient(135deg, #0b2c6b, #1d56d9); 
                   border-radius: 20px; 
                   overflow: hidden;">
        <tr>
          <td style="padding:26px 26px 28px;">

            <!-- Badges -->
            <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px;">
              <tr>
                <td style="padding-right:8px;">
                  <span style="display:inline-block; background:#ffffff; color:#0b2c6b; font-family:Arial,Helvetica,sans-serif; font-size:11px; font-weight:700; letter-spacing:1px; text-transform:uppercase; padding:8px 18px; border-radius:50px;">
                    <?= htmlspecialchars($badge1) ?>
                  </span>
                </td>
                <td style="padding-right:8px;">
                  <span style="display:inline-block; background:#ffffff; color:#0b2c6b; font-family:Arial,Helvetica,sans-serif; font-size:11px; font-weight:700; letter-spacing:1px; text-transform:uppercase; padding:8px 18px; border-radius:50px;">
                    <?= htmlspecialchars($badge2) ?>
                  </span>
                </td>
                <td>
                  <span style="display:inline-block; background:#ffffff; color:#0b2c6b; font-family:Arial,Helvetica,sans-serif; font-size:11px; font-weight:700; letter-spacing:1px; text-transform:uppercase; padding:8px 18px; border-radius:50px;">
                    <?= htmlspecialchars($badge3) ?>
                  </span>
                </td>
              </tr>
            </table>

            <!-- Overall PCL AI Rating -->
            <div style="font-family:Arial,Helvetica,sans-serif; font-size:11px; font-weight:700; letter-spacing:1.5px; text-transform:uppercase; color:#b0d0ff; margin-bottom:8px;">
              OVERALL PCL AI RATING
            </div>
            
            <div style="font-family:Georgia,'Times New Roman',serif; font-size:62px; font-weight:700; color:#ffffff; line-height:1; margin-bottom:20px;">
              <?= htmlspecialchars($overallRating) ?>
            </div>

            <!-- Selected Band -->
            <div style="display:inline-block; background:#ffffff; color:#0b2c6b; font-family:Arial,Helvetica,sans-serif; font-size:11px; font-weight:700; letter-spacing:1px; text-transform:uppercase; padding:8px 22px; border-radius:50px; margin-bottom:24px;">
              &#10003;&nbsp; <?= htmlspecialchars($selectionBand) ?>
            </div>

            <!-- Selection Confidence -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:8px;">
              <tr>
                <td style="font-family:Arial,Helvetica,sans-serif; font-size:11px; font-weight:700; letter-spacing:1px; text-transform:uppercase; color:#b0d0ff;">
                  SELECTION CONFIDENCE METER
                </td>
                <td align="right" style="font-family:Georgia,'Times New Roman',serif; font-size:15px; font-weight:700; color:#ffffff;">
                  <?= number_format($meterPct, 2) ?>%
                </td>
              </tr>
            </table>

            <!-- Progress Bar -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:8px; background:rgba(255,255,255,0.15); height:10px; border-radius:50px; overflow:hidden;">
              <tr>
                <td width="<?= $meterPct ?>%" style="background: linear-gradient(to right, #ef4444, #f97316, #eab308, #84cc16); height:10px; font-size:0; line-height:0;">&nbsp;</td>
                <td width="<?= 100 - $meterPct ?>%" style="background:rgba(255,255,255,0.15); height:10px; font-size:0; line-height:0;">&nbsp;</td>
              </tr>
            </table>

            <!-- Low Medium High -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <td style="font-family:Arial,Helvetica,sans-serif; font-size:9px; color:#b0d0ff; text-transform:uppercase; letter-spacing:0.5px;">LOW</td>
                <td align="center" style="font-family:Arial,Helvetica,sans-serif; font-size:9px; color:#b0d0ff; text-transform:uppercase; letter-spacing:0.5px;">MEDIUM</td>
                <td align="right" style="font-family:Arial,Helvetica,sans-serif; font-size:9px; color:#b0d0ff; text-transform:uppercase; letter-spacing:0.5px;">HIGH</td>
              </tr>
            </table>

          </td>
        </tr>
      </table>
    </td>
  </tr>
  <!-- ══ END AI RATING ══ -->


   <!-- ══════════════════════════════════════════ CORPORATE WORLD CUP ══════════════════════════════════════════ -->
  <tr>
    <td style="padding:24px 28px 0;">
        <table width="100%" cellpadding="0" cellspacing="0" style="margin-top:15px;" align="center">
            <tr>
                <td align="center">
                    <img src="https://wplspeedqueen.com/email_api/cwctrophy.png" style="height:240px; object-fit:cover;">             
                </td>    
            </tr>
            <tr>
                <td align="center">
                    <p style="text-align:center;">
                        As part of the Corporate World Cup structure, only one corporate team per sector is permitted in each city, 
                        ensuring exclusive category representation throughout the journey to the Corporate World Cup National Finals.
                    </p>
                </td>
            </tr>
        </table> 
        
        
        <table width="100%" cellpadding="0" cellspacing="0" style="margin-top:15px;" align="center">
            <tr>
                <td align="center"> 
                    <h4>
                        WHAT'S INCLUDED IN THE CORPORATE WORLD CUP™ QUALIFICATION PACKAGE
                    </h4>
                </td>
            <tr>    
            <tr>
                <td align="center">
                    <img src="https://wplspeedqueen.com/email_api/cwcmerchandise.jpeg" style="width:100%;height:auto;display:block;">           
                </td>    
            </tr>
            <tr>
                <td>
                    <h2 style="font-family: Arial, sans-serif; font-size: 18px; font-weight: bold; color: #1a1a2e; margin: 0 0 12px;">
                    🏏 Premium Team Merchandise <span style="font-size: 14px; font-weight: normal; color: #666;">(30 Players)</span>
                    </h2>
                    <ul style="font-family: Arial, sans-serif; font-size: 15px; color: #333; line-height: 1.8; padding-left: 0; list-style: none; margin: 0 0 28px;">
                    <li>👕 30 Customized White Match Jerseys</li>
                    <li>👕 30 Customized Colored Match Jerseys</li>
                    <li>👖 30 White Track Pants / Lowers</li>
                    <li>👖 30 Colored Track Pants / Lowers</li>
                    <li>🩳 30 Practice Shorts</li>
                    <li>🧥 30 Premium Team Jackets</li>
                    <li>🧢 60 Customized Team Caps</li>
                    <li>🎒 30 Premium Team Kit Bags</li>
                    <li>🎒 30 Premium Shoulder Travel / Pithu Bags</li>
                    </ul>

                    <h2 style="font-family: Arial, sans-serif; font-size: 18px; font-weight: bold; color: #1a1a2e; margin: 0 0 12px;">
                    ✏️ Customization Included
                    </h2>
                    <ul style="font-family: Arial, sans-serif; font-size: 15px; color: #333; line-height: 1.8; padding-left: 0; list-style: none; margin: 0 0 28px;">
                    <li>🏢 Company Logo Branding</li>
                    <li>🏆 Team Name Branding</li>
                    <li>👤 Player Name Printing</li>
                    <li>🔢 Player Number Printing</li>
                    <li>📌 Optional Sponsor Branding Locations</li>
                    </ul>

                    <h2 style="font-family: Arial, sans-serif; font-size: 18px; font-weight: bold; color: #1a1a2e; margin: 0 0 12px;">
                    📣 Corporate Visibility Benefits
                    </h2>
                    <ul style="font-family: Arial, sans-serif; font-size: 15px; color: #333; line-height: 1.8; padding-left: 0; list-style: none; margin: 0 0 28px;">
                    <li>👁️ Live Match Visibility</li>
                    <li>📱 Social Media Exposure</li>
                    <li>🎬 Highlights Packages</li>
                    <li>🎤 Interviews &amp; Presentations</li>
                    <li>📸 Team Photos &amp; Celebrations</li>
                    <li>📰 Digital &amp; Print Publicity</li>
                    <li>🌍 Brand Exposure Across The Corporate World Cup™ Ecosystem For The Next 12 Months</li>
                    </ul>
                </td>
            </tr>
        </table> 
    </td>
  </tr>

  <!-- end corporate world cup -->


  




  <!-- ══════════════════════════════════════════PCL AI RATING & RECOMMENDATION══════════════════════════════════════════ -->
  <tr>
    <td style="padding:24px 28px 0;">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" 
            style="border:1px solid #dde3ee; background-color:#f8fafd; border-radius:16px; overflow:hidden;">
        
        <tr>
          <td style="padding:32px 28px 32px;">
            
            <!-- Title -->
            <div style="font-family:Georgia,'Times New Roman',serif; font-size:27px; font-weight:700; color:#0f172a; margin-bottom:18px; text-align:center;">
              PCL Corporate Intelligence Review
            </div>

            <!-- Premium Badge -->
            <div style="text-align:center; margin-bottom:24px;">
              <span style="display:inline-block; background:#e0f2fe; color:#0e7490; font-family:Arial,Helvetica,sans-serif; font-size:11.5px; font-weight:700; padding:7px 24px; border-radius:50px; letter-spacing:0.5px; border:1px solid #bae6fd;">
                <span style="color:#22c55e; font-size:13px;">●</span> AI Evaluation Outcome: Premium Corporate Cricket Unit
              </span>
            </div>
            

            <!-- Four Cards -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="8" border="0" style="margin-bottom:26px;">
              <tr>
                <!-- AI Rating -->
                <?php
                $grades = [
                  ['val'=> (int)$readiness . '/100', 'lbl'=>'AI Rating'],
                  ['val'=> $overallGrade, 'lbl'=>'Grade'],
                  ['val'=> $battingGrade, 'lbl'=>'Batting Grade'],
                  ['val'=> $bowlingGrade, 'lbl'=>'Bowling Grade'],
                ];
                foreach ($grades as $g):
                ?>
                
                <!-- Grade -->
                <td width="25%">
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#ffffff; border:1px solid #e2e8f0; border-radius:12px;">
                    <tr>
                      <td align="center" style="padding:18px 12px 15px;">
                        <div style="font-family:Georgia,'Times New Roman',serif; font-size:29px; font-weight:700; color:#1e40af; line-height:1;"><?= htmlspecialchars($g['val']) ?></div>
                        <div style="font-family:Arial,Helvetica,sans-serif; font-size:9.5px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.6px; margin-top:6px;"><?= $g['lbl'] ?></div>
                      </td>
                    </tr>
                  </table>
                </td>
                <?php endforeach; ?>
              </tr>
            </table>

            <!-- Recommendation -->
            <div style="font-family:Arial,Helvetica,sans-serif; font-size:13.2px; line-height:1.85; color:#334155; margin-bottom:16px;">
              <strong style="color:#0f172a;">PCL AI Recommendation:</strong> <?= htmlspecialchars($aiRecommendation ?? 'Strong corporate team profile with proven match sample, winning conversion and squad depth for PCL Season 12 review.') ?>
            </div>

            <!-- Bullet Points -->
            <?php if(!empty($strengths)): ?>
            <ul style="margin:0; padding-left:20px; font-family:Arial,Helvetica,sans-serif; font-size:13.1px; line-height:1.85; color:#334155;">
              <?php foreach(array_slice($strengths, 0, 5) as $s): ?>
                <?php if(trim($s) !== ''): ?>
                <li style="margin-bottom:7px;"><?= htmlspecialchars($s) ?></li>
                <?php endif; ?>
              <?php endforeach; ?>
            </ul>
            <?php endif; ?>

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

  <!-- end -->


  <!-- ══════════════════════════════════════════HALL OF FAME SECTION══════════════════════════════════════════ -->
  <?php if (!empty($topPerf)): ?>
  <tr>
    <td style="padding:28px 24px 0;">

      <!-- Section Heading -->
      <div style="text-align:center;font-family:Arial,Helvetica,sans-serif;font-size:16px;font-weight:900;color:#0d1f4c;letter-spacing:3px;text-transform:uppercase;margin-bottom:20px;">
        <?= htmlspecialchars($teamName) ?> Players in PCL Hall of Fame Top 100
      </div>

      <!-- Light blue gradient card -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
             style="background:#e8eef8;border-radius:18px;">
        <tr>
          <td style="padding:24px 12px 28px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>

                <?php
                $hofPlayers = array_values(array_slice($topPerf, 0, 5));
                foreach ($hofPlayers as $i => $p):

                  $pos      = (int)$i + 1;
                  $isTop3   = $pos <= 3;
                  $emoji    = $topBadgeEmoji[(string)$pos] ?? '';
                  $pName    = $p['player_name'] ?? 'Player';
                  $pInitial = pclInitials($pName);
                  $pImg     = getPlayerImageUrl($teamIdParam, $p);
                  $pRank    = getPlayerRank($p);
                  $pRuns    = getPlayerRuns($p);
                  $pWkts    = getPlayerWickets($p);
                  $statStr  = $p['stats'] ?? (($pRuns ? $pRuns.' Runs' : '') . ($pWkts ? ' / '.$pWkts.' Wkts' : ''));
                  if (empty($statStr)) { $statStr = '—'; }
                  $showImage = false;
                  if (!empty($pImg)) {
                    $headers = @get_headers($pImg);
                    if ($headers && strpos($headers[0], '200') !== false) { $showImage = true; }
                  }
                  $rankBg  = $isTop3 ? 'linear-gradient(135deg,#f5d57a 0%,#e8b830 100%)' : '#0d1f4c';
                  $rankClr = $isTop3 ? '#1a1200' : '#e8b830';
                ?>

                <td align="center" valign="top" width="20%" style="padding:0 4px;">

                  <!-- TOP badge pill OR spacer -->
                  <?php if ($isTop3): ?>
                    <div style="display:inline-block;background:linear-gradient(135deg,#f5d57a 0%,#e8b830 100%);color:#1a1200;font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:800;padding:6px 16px;border-radius:50px;margin-bottom:12px;letter-spacing:0.3px;">
                      <?= $emoji ?> TOP <?= $pos ?>
                    </div>
                  <?php else: ?>
                    <div style="height:30px;margin-bottom:12px;">&nbsp;</div>
                  <?php endif; ?>

                  <!-- Circular avatar with gold border -->
                  <div style="width:86px;height:86px;margin:0 auto 12px;border:4px solid #e8b830;border-radius:50%;overflow:hidden;background:#0d2a6e;text-align:center;line-height:78px;">
                    <?php if ($showImage): ?>
                      <img src="<?= htmlspecialchars($pImg) ?>" width="86" height="86"
                           alt="<?= htmlspecialchars($pName) ?>"
                           style="display:block;width:86px;height:86px;border-radius:50%;border:0;object-fit:cover;">
                    <?php else: ?>
                      <span style="font-size:24px;font-weight:800;color:#ffffff;font-family:Arial,Helvetica,sans-serif;">
                        <?= htmlspecialchars($pInitial) ?>
                      </span>
                    <?php endif; ?>
                  </div>

                  <!-- PCL Rank pill -->
                  <div style="display:inline-block;background:<?= $rankBg ?>;color:<?= $rankClr ?>;font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:800;padding:5px 14px;border-radius:50px;margin-bottom:8px;">
                    <?= htmlspecialchars($pRank ? 'PCL #'.$pRank : '#'.$pos) ?>
                  </div>

                  <!-- Player name -->
                  <div style="font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:800;color:#0d1f4c;margin-bottom:8px;line-height:1.3;">
                    <?= htmlspecialchars($pName) ?>
                  </div>

                  <!-- Stat pill -->
                  <div style="display:inline-block;background:#ffffff;border:1px solid #dde6f4;border-radius:50px;padding:6px 14px;font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:700;color:#c87a00;">
                    <?= htmlspecialchars($statStr) ?>
                  </div>

                </td>

                <?php endforeach; ?>
              </tr>
            </table>
          </td>
        </tr>
      </table>

    </td>
  </tr>
  <?php endif; ?>
  <!-- ══ END HALL OF FAME ══ -->


  <!-- ══════════════════════════════════════════ALL-TIME BEST 5 SECTION══════════════════════════════════════════ -->
  <?php if (!empty($playersSorted)): ?>
  <tr>
    <td style="padding:20px 24px 0;">

      <!-- Section Heading -->
      <div style="text-align:center;font-family:Arial,Helvetica,sans-serif;font-size:16px;font-weight:900;color:#0d1f4c;letter-spacing:3px;text-transform:uppercase;margin-bottom:20px;">
        <?= htmlspecialchars($teamName) ?> All-Time Best 5 Profiles
      </div>

      <!-- Light blue gradient card -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
             style="background:#e8eef8;border-radius:18px;">
        <tr>
          <td style="padding:24px 12px 28px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>

                <?php
                $best5 = array_values(array_slice($playersSorted, 0, 5));
                foreach ($best5 as $i => $p):

                  $pos      = (int)$i + 1;
                  $isTop3   = $pos <= 3;
                  $emoji    = $topBadgeEmoji[(string)$pos] ?? '';
                  $pName    = $p['player_name'] ?? 'Player';
                  $pInitial = pclInitials($pName);
                  $pImg     = getPlayerImageUrl($teamIdParam, $p);
                  $pRuns    = getPlayerRuns($p);
                  $pWkts    = getPlayerWickets($p);
                  $statStr  = ($pRuns ? $pRuns.' Runs' : '') . ($pWkts ? ' / '.$pWkts.' Wkts' : '');
                  if (empty($statStr)) { $statStr = '—'; }
                  $showImage = false;
                  if (!empty($pImg)) {
                    $headers = @get_headers($pImg);
                    if ($headers && strpos($headers[0], '200') !== false) { $showImage = true; }
                  }
                  $rankBg  = $isTop3 ? 'linear-gradient(135deg,#f5d57a 0%,#e8b830 100%)' : '#0d1f4c';
                  $rankClr = $isTop3 ? '#1a1200' : '#e8b830';
                ?>

                <td align="center" valign="top" width="20%" style="padding:0 4px;">

                  <!-- TOP badge pill OR spacer -->
                  <?php if ($isTop3): ?>
                    <div style="display:inline-block;background:linear-gradient(135deg,#f5d57a 0%,#e8b830 100%);color:#1a1200;font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:800;padding:6px 16px;border-radius:50px;margin-bottom:12px;letter-spacing:0.3px;">
                      <?= $emoji ?> TOP <?= $pos ?>
                    </div>
                  <?php else: ?>
                    <div style="height:30px;margin-bottom:12px;">&nbsp;</div>
                  <?php endif; ?>

                  <!-- Circular avatar with gold border -->
                  <div style="width:86px;height:86px;margin:0 auto 12px;border:4px solid #e8b830;border-radius:50%;overflow:hidden;background:#0d2a6e;text-align:center;line-height:78px;">
                    <?php if ($showImage): ?>
                      <img src="<?= htmlspecialchars($pImg) ?>" width="86" height="86"
                           alt="<?= htmlspecialchars($pName) ?>"
                           style="display:block;width:86px;height:86px;border-radius:50%;border:0;object-fit:cover;">
                    <?php else: ?>
                      <span style="font-size:24px;font-weight:800;color:#ffffff;font-family:Arial,Helvetica,sans-serif;">
                        <?= htmlspecialchars($pInitial) ?>
                      </span>
                    <?php endif; ?>
                  </div>

                  <!-- Rank pill (#1, #2 ... not PCL rank) -->
                  <div style="display:inline-block;background:<?= $rankBg ?>;color:<?= $rankClr ?>;font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:800;padding:5px 14px;border-radius:50px;margin-bottom:8px;">
                    #<?= $pos ?>
                  </div>

                  <!-- Player name -->
                  <div style="font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:800;color:#0d1f4c;margin-bottom:8px;line-height:1.3;">
                    <?= htmlspecialchars($pName) ?>
                  </div>

                  <!-- Stat pill -->
                  <div style="display:inline-block;background:#ffffff;border:1px solid #dde6f4;border-radius:50px;padding:6px 14px;font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:700;color:#c87a00;">
                    <?= htmlspecialchars($statStr) ?>
                  </div>

                </td>

                <?php endforeach; ?>
              </tr>
            </table>
          </td>
        </tr>
      </table>

    </td>
  </tr>
  <?php endif; ?>
  <!-- ══ END ALL-TIME BEST 5 ══ -->

  <!-- ══════════════════════════════════════════ INTRODUCING PCL TEST TWENTY ══════════════════════════════════════════ -->
  <tr>
    <td style="padding:28px 28px 0;">

      <!-- OUTER CARD with rounded border + blue top accent -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
            style="border:2px solid #dde3ee;border-radius:20px;overflow:hidden;background-color:#f8fafd;">

        <!-- Blue top accent bar -->
        <tr><td height="6" style="background:linear-gradient(90deg,#0b2c6b 0%,#1d56d9 100%);line-height:6px;font-size:6px;">&nbsp;</td></tr>

        <tr>
          <td style="padding:32px 28px 32px;">

            <!-- Section Label -->
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:700;color:#1d56d9;letter-spacing:2px;text-transform:uppercase;margin-bottom:12px;">
              Introducing PCL Test Twenty
            </div>

            <!-- Headline + Subtext Two Column -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:28px;">
              <tr>
                <!-- Left: Big Headline -->
                <td width="52%" valign="top" style="padding-right:24px;">
                  <div style="font-family:Georgia,'Times New Roman',serif;font-size:28px;font-weight:700;color:#04122b;line-height:1.2;">
                    Corporate teams need different squads for different formats.
                  </div>
                </td>
                <!-- Right: Subtext -->
                <td width="48%" valign="middle">
                  <div style="font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#64748b;line-height:1.7;">
                    The right man, in the right place, at the right time. Team India has different squads for T20, ODI and Test &mdash; corporate teams should also unlock diverse employee talent pools.
                  </div>
                </td>
              </tr>
            </table>

            <!-- 3 Dark Gradient Format Cards -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>

                <?php
                $formatCards = [
                  [
                    'tag'   => '40 OVERS &bull; CRICKET FOURTH FORMAT',
                    'title' => 'PCL Test Twenty',
                    'desc'  => 'The true test of endurance, patience and technique for steady professionals who plan, adapt and last the distance.',
                    'points'=> ['Longer involvement for more players', 'Leadership and patience under pressure', 'Perfect for corporate depth building'],
                    'bg'    => 'background-color:#0d5c63;',
                  ],
                  [
                    'tag'   => '20 OVERS &bull; SEASON 12',
                    'title' => 'Pro Corporate League T20',
                    'desc'  => 'Fast-paced and thrilling for bold hitters, crafty bowlers and agile fielders who thrive under pressure.',
                    'points'=> ['Core city edition format', 'High-pressure match environment', 'Corporate champion pathway'],
                    'bg'    => 'background-color:#1a3ab8;',
                  ],
                  [
                    'tag'   => '11 OVERS &bull; CORPORATE T11',
                    'title' => 'The Corporate T11',
                    'desc'  => 'Breakneck-speed cricket for fearless decision-makers, risk-takers and innovators who can turn the match in minutes.',
                    'points'=> ['High-energy short format', 'Perfect for busy corporate teams', 'Fast content and highlight generation'],
                    'bg'    => 'background-color:#6b2d0e;',
                  ],
                ];
                foreach ($formatCards as $idx => $fc):
                  $isLast = ($idx === count($formatCards) - 1);
                ?>

                <td width="33%" valign="top" style="padding:<?= $isLast ? '0' : '0 10px 0 0' ?>;">
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                        style="<?= $fc['bg'] ?>border-radius:16px;overflow:hidden;">
                    <tr>
                      <td style="padding:22px 20px 26px;vertical-align:top;">

                        <!-- Tag pill -->
                        <div style="display:inline-block;background-color:rgba(255,255,255,0.15);border-radius:50px;padding:6px 14px;font-family:Arial,Helvetica,sans-serif;font-size:9px;font-weight:700;color:#ffffff;letter-spacing:0.8px;text-transform:uppercase;margin-bottom:18px;">
                          <?= $fc['tag'] ?>
                        </div>

                        <!-- Title -->
                        <div style="font-family:Georgia,'Times New Roman',serif;font-size:20px;font-weight:700;color:#ffffff;margin-bottom:12px;line-height:1.3;">
                          <?= $fc['title'] ?>
                        </div>

                        <!-- Description -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:12px;color:rgba(255,255,255,0.85);line-height:1.7;margin-bottom:16px;">
                          <?= $fc['desc'] ?>
                        </div>

                        <!-- Bullet Points -->
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                          <?php foreach ($fc['points'] as $pt): ?>
                          <tr>
                            <td valign="top" style="padding:3px 0;">
                              <table role="presentation" cellpadding="0" cellspacing="0" border="0">
                                <tr>
                                  <td valign="top" style="padding-right:8px;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:rgba(255,255,255,0.7);">&#8226;</td>
                                  <td style="font-family:Arial,Helvetica,sans-serif;font-size:12px;color:rgba(255,255,255,0.85);line-height:1.6;">
                                    <?= $pt ?>
                                  </td>
                                </tr>
                              </table>
                            </td>
                          </tr>
                          <?php endforeach; ?>
                        </table>

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

                <?php endforeach; ?>

              </tr>
            </table>

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

    </td>
  </tr>
  <!-- ══ END PCL TEST TWENTY ══ -->


  <!-- ══════════════════════════════════════════SELECTION MESSAGE══════════════════════════════════════════ -->
  <tr>
    <td style="padding:32px 28px 0;">
      <!-- QUALIFICATION WINDOW BOX -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border:1px solid #d7af59;background-color:#fdfaf0;margin-bottom:0;">
        <tr><td style="height:4px;background-color:#d7af59;font-size:0;line-height:0;">&nbsp;</td></tr>
         <tr>
          <td style="padding:24px 24px 8px;">
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:9px;font-weight:700;color:#7a5500;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:8px;">&#9670; Limited Qualification Window</div>
            <div style="font-family:Georgia,'Times New Roman',serif;font-size:28px;font-weight:700;color:#04122b;margin-bottom:12px;line-height:1.2;">Only 8 qualification slots will move forward.</div>
            <p><strong>17 corporate teams are currently under review for your city cluster.</strong></p>
            <tr>
              <td style="padding:0 24px 24px;">
                <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">
                  <tr>
                    <!-- New Buttons -->
                    <td align="center" style="padding:4px;">
                      <a href="https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile_new.php?lead_id=20001&team_id=<?= $teamIdParam ?>&team_name=<?= urlencode($teamName) ?>&source=email&source_data=reserve"
                        style="display:inline-block;background-color:white;color:#d7af59;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:700;padding:11px 20px;border:1px solid #d7af59;letter-spacing:0.5px;white-space:nowrap;">
                        Reserve Qualification Slot
                      </a>
                    </td>
                    
                    <td align="center" style="padding:4px;">
                      <a href="https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile_new.php?lead_id=20001&team_id=<?= $teamIdParam ?>&team_name=<?= urlencode($teamName) ?>&source=email&source_data=talk_to_team"
                        style="display:inline-block;background-color:white;color:#d7af59;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:700;padding:11px 20px;border:1px solid #d7af59;letter-spacing:0.5px;white-space:nowrap;">
                        Talk To PCL Team
                      </a>
                    </td>
                    
                    <td align="center" style="padding:4px;">
                      <a href="https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile_new.php?lead_id=20001&team_id=<?= $teamIdParam ?>&team_name=<?= urlencode($teamName) ?>&source=email&source_data=need_more_time"
                        style="display:inline-block;background-color:white;color:#d7af59;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:700;padding:11px 20px;border:1px solid #cbd5e1;letter-spacing:0.5px;white-space:nowrap;">
                        Need more time
                      </a>
                    </td>
                  </tr>
                </table>
                <p><span>Your slot remains active for 72 hours.</span></p>
              </td>
            </tr>
          </td>
        </tr>

        <tr>
          <td style="padding:0 24px 24px;">
            <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">
              <tr>
                <td align="center" style="padding:4px;">
                  <a href="https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile_new.php?lead_id=20001&team_id=<?= $teamIdParam ?>&team_name=<?= urlencode($teamName) ?>&source=email&source_data=reserve"
                    style="display:inline-block;background-color:#04122b;color:#d7af59;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:700;padding:11px 20px;border:1px solid #d7af59;letter-spacing:0.5px;">Reserve</a>
                </td>
                <td align="center" style="padding:4px;">
                  <a href="https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile_new.php?lead_id=20001&team_id=<?= $teamIdParam ?>&team_name=<?= urlencode($teamName) ?>&source=email&source_data=confirm"
                    style="display:inline-block;background-color:#d7af59;color:#04122b;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:700;padding:11px 20px;border:1px solid #d7af59;letter-spacing:0.5px;">Confirm</a>
                </td>
                <td align="center" style="padding:4px;">
                  <a href="https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile_new.php?lead_id=20001&team_id=<?= $teamIdParam ?>&team_name=<?= urlencode($teamName) ?>&source=email&source_data=not_interest"
                    style="display:inline-block;background-color:#f1f5f9;color:#64748b;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:700;padding:11px 20px;border:1px solid #cbd5e1;letter-spacing:0.5px;">Not Interested</a>
                </td>
                <td align="center" style="padding:4px;">
                  <a href="https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile_new.php?lead_id=20001&team_id=<?= $teamIdParam ?>&team_name=<?= urlencode($teamName) ?>&source=email&source_data=skip"
                    style="display:inline-block;background-color:#f1f5f9;color:#64748b;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:700;padding:11px 20px;border:1px solid #cbd5e1;letter-spacing:0.5px;">Skip</a>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </td>
  </tr>

  <!-- new -->
   <tr>
    <td style="padding:32px 28px 0;">
     
       <p>
        <strong>Next Qualification Steps</strong>
        <ul class="qualification-steps">
            <li>Qualification slot reservation</li>
            <li>Team verification &amp; management onboarding</li>
            <li>PCL Season 12 corporate allocation</li>
            <li>Challenger qualification mapping</li>
            <li>#CorporateKaWorldCup pathway activation</li>
        </ul>
      </p>
    </td>
  </tr>
  <!-- ══ END SELECTION ══ -->

  <!-- ══════════════════════════════════════════CORPORATE BOARD SUMMARY══════════════════════════════════════════ -->
  <tr>
    <td style="padding:24px 28px 0;">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
             style="border:1px solid #dde3ee; background-color:#f8fafd; border-radius:16px; overflow:hidden;">

        <tr><td height="6" style="background:#0d2a5e; line-height:6px; font-size:6px;">&nbsp;</td></tr>

        <tr>
          <td style="padding:32px 28px 32px;">

            <!-- Title -->
            <div style="font-family:Georgia,'Times New Roman',serif; font-size:26px; font-weight:700; color:#04122b; margin-bottom:12px;">
              <?= htmlspecialchars($teamName);?> Corporate Board Summary
            </div>

            <!-- Description -->
            <p style="margin:0 0 32px; font-family:Arial,Helvetica,sans-serif; font-size:13px; line-height:1.8; color:#4a5568;">
              <strong style="color:#04122b;">Corporate dominance summary:</strong> <?= htmlspecialchars($teamName) ?> is presented as a public corporate cricket unit with PCL match history,
              mapped player depth and Cric Heroes profile evidence for broader team validation.
            </p>

            <!-- Two column layout -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>

                <!-- ── PCL Matches Summary ── -->
                <td width="50%" style="padding-right:16px; vertical-align:top;">
                  <div style="font-family:Georgia,'Times New Roman',serif; font-size:16px; font-weight:700; color:#04122b; margin-bottom:18px;">
                    PCL Matches Summary
                  </div>

                  <!-- PCL Row 1 -->
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:8px;">
                    <tr>
                      <td width="33%" style="padding-right:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($pcl_matches) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">PCL MATCHES</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                      <td width="33%" style="padding-left:4px; padding-right:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($pcl_wins) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">PCL WINS</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                      <td width="34%" style="padding-left:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($pcl_win_rate_display) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">PCL WIN RATE</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                  </table>

                  <!-- PCL Row 2 -->
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                      <td width="33%" style="padding-right:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($pcl_runs) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">PCL RUNS</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                      <td width="33%" style="padding-left:4px; padding-right:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($pcl_wickets) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">PCL WICKETS</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                      <td width="34%" style="padding-left:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($pcl_run_rate) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">RUN RATE</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                  </table>

                </td><!-- end PCL column -->

                <!-- ── Cric Heroes Matches Summary ── -->
                <td width="50%" style="padding-left:16px; vertical-align:top;">
                  <div style="font-family:Georgia,'Times New Roman',serif; font-size:16px; font-weight:700; color:#04122b; margin-bottom:18px;">
                    Cric Heroes Matches Summary
                  </div>

                  <!-- CH Row 1 -->
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:8px;">
                    <tr>
                      <td width="33%" style="padding-right:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($ch_matches) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">CH MATCHES</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                      <td width="33%" style="padding-left:4px; padding-right:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($ch_wins) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">CH WINS</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                      <td width="34%" style="padding-left:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($ch_win_rate_display) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">CH WIN RATE</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                  </table>

                  <!-- CH Row 2 -->
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                      <td width="33%" style="padding-right:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= htmlspecialchars($ch_members) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">MEMBERS</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                      <td width="33%" style="padding-left:4px; padding-right:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= count($ch_batting) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">BATTING CORE</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                      <td width="34%" style="padding-left:4px;">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                               style="background:#ffffff; border:1px solid #dde3ee; border-radius:12px;">
                          <tr>
                            <td style="padding:16px 8px 14px; text-align:center; font-family:Georgia,'Times New Roman',serif; font-size:18px; font-weight:700; color:#d7af59; line-height:1.2;">
                              <?= count($ch_bowling) ?><br>
                              <span style="font-family:Arial,Helvetica,sans-serif; font-size:9px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.4px;">BOWLING CORE</span>
                            </td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                  </table>

                </td><!-- end CH column -->

              </tr>
            </table>

          </td>
        </tr>
      </table>
    </td>
  </tr>
 <!-- ══ END BOARD SUMMARY ══ -->

  <!-- Ruhi New start -->

  <!-- ══════════════════════════════════════════ DIVISION-WISE RANKING & ELITE PATHWAY leaderboard section ══════════════════════════════════════════ -->
  <tr>
    <td style="padding:28px 28px 0;">

      <!-- OUTER CARD with rounded border + blue top accent -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
            style="border:2px solid #dde3ee;border-radius:20px;overflow:hidden;background-color:#f8fafd;">

        <!-- Blue top accent bar -->
        <tr><td height="6" style="background:linear-gradient(90deg,#0b2c6b 0%,#1d56d9 100%);line-height:6px;font-size:6px;">&nbsp;</td></tr>

        <tr>
          <td style="padding:28px 28px 28px;">

            <!-- Section Label -->
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:700;color:#1d56d9;letter-spacing:2px;text-transform:uppercase;margin-bottom:10px;">
              Division-Wise Ranking &amp; Elite Pathway
            </div>

            <!-- Headline -->
            <div style="font-family:Georgia,'Times New Roman',serif;font-size:28px;font-weight:700;color:#04122b;line-height:1.2;margin-bottom:16px;">
              Every match contributes to a national corporate leaderboard.
            </div>

            <!-- Sub-text -->
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#64748b;line-height:1.7;margin-bottom:24px;">
              Rankings are calculated through match wins, net run rate, discipline points and participation consistency across the 3-format season.
            </div>

            <!-- Top 4 Numbered Cards Row -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:12px;">
              <tr>
                <?php
                $eliteCards = [
                  ['num'=>'01','title'=>'City Ranking','desc'=>'Every corporate team enters its city leaderboard.'],
                  ['num'=>'02','title'=>'National Rank','desc'=>'Aggregated performance across city editions.'],
                  ['num'=>'03','title'=>'Top 2 Promotion','desc'=>'Best teams from each city move to Elite Division.'],
                  ['num'=>'04','title'=>'PCL Eleven 11','desc'=>'Elite pathway to national broadcast opportunities.'],
                ];
                foreach ($eliteCards as $card):
                ?>
                <td width="25%" valign="top" style="padding:0 5px 0 0;">
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                        style="background-color:#ffffff;border:1.5px solid #dde3ee;border-radius:14px;overflow:hidden;">
                    <tr>
                      <td style="padding:18px 16px 16px;">
                        <!-- Number badge -->
                        <div style="display:inline-block;background-color:#04122b;color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:700;padding:6px 12px;border-radius:8px;margin-bottom:14px;">
                          <?= $card['num'] ?>
                        </div>
                        <!-- Title -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:13px;font-weight:700;color:#04122b;margin-bottom:6px;line-height:1.3;">
                          <?= $card['title'] ?>
                        </div>
                        <!-- Description -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:9px;color:#64748b;line-height:1.6;">
                          <?= $card['desc'] ?>
                        </div>
                      </td>
                    </tr>
                  </table>
                </td>
                <?php endforeach; ?>
              </tr>
            </table>

            <!-- Bottom 4 Icon Cards Row -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <?php
                $iconCards = [
                  ['icon'=>'📺','title'=>'Broadcast Pathway','desc'=>'Top players shortlisted for PCL Eleven 11 live-coverage opportunities.'],
                  ['icon'=>'🎥','title'=>'Digital Stories','desc'=>'Player highlights, interviews and team features for social visibility.'],
                  ['icon'=>'🏆','title'=>'Legend Access','desc'=>'Senior management meets, trophy moments and premium event access.'],
                  ['icon'=>'🤝','title'=>'Sponsor Access','desc'=>'Priority access to PCL sponsorship and corporate collaborations.'],
                ];
                foreach ($iconCards as $ic):
                ?>
                <td width="25%" valign="top" style="padding:0 5px 0 0;">
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                        style="background-color:#ffffff;border:1.5px solid #dde3ee;border-radius:14px;overflow:hidden;">
                    <tr>
                      <td style="padding:18px 16px 16px;">
                        <!-- Icon -->
                        <div style="font-size:22px;margin-bottom:12px;line-height:1;"><?= $ic['icon'] ?></div>
                        <!-- Title -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:700;color:#04122b;margin-bottom:6px;line-height:1.3;">
                          <?= $ic['title'] ?>
                        </div>
                        <!-- Description -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:9px;color:#64748b;line-height:1.6;">
                          <?= $ic['desc'] ?>
                        </div>
                      </td>
                    </tr>
                  </table>
                </td>
                <?php endforeach; ?>
              </tr>
            </table>

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

    </td>
  </tr>
 <!-- ══ END DIVISION-WISE RANKING leaderboard section ══ -->

  <!-- ══════════════════════════════════════════ CORPORATE BENEFITS ══════════════════════════════════════════ -->
  <tr>
    <td style="padding:28px 28px 0;">

      <!-- OUTER CARD with rounded border + blue top accent -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
            style="border:2px solid #dde3ee;border-radius:20px;overflow:hidden;background-color:#f8fafd;">

        <!-- Blue top accent bar -->
        <!-- <tr><td height="6" style="background:linear-gradient(90deg,#0b2c6b 0%,#1d56d9 100%);line-height:6px;font-size:6px;">&nbsp;</td></tr> -->

        <tr>
          <td style="padding:32px 28px 32px;">

            <!-- Section Label -->
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:700;color:#1d56d9;letter-spacing:2px;text-transform:uppercase;margin-bottom:12px;">
              Corporate Benefits
            </div>

            <!-- Headline + Subtext Two Column -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:28px;">
              <tr>
                <!-- Left: Big Headline -->
                <td width="55%" valign="top" style="padding-right:24px;">
                  <div style="font-family:Georgia,'Times New Roman',serif;font-size:28px;font-weight:700;color:#04122b;line-height:1.2;">
                    AI-verified cricket that HR, leadership and brand teams can all use.
                  </div>
                </td>
                <!-- Right: Subtext -->
                <td width="45%" valign="middle">
                  <div style="font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#64748b;line-height:1.7;">
                    PCL converts a corporate team into a full employee-engagement, wellness, employer-branding and leadership-recognition property.
                  </div>
                </td>
              </tr>
            </table>

            <!-- 3 Benefit Cards Row -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>

                <?php
                $benefitCards = [
                  [
                    'icon'    => '🤝',
                    'tag'     => 'HR + CULTURE',
                    'title'   => 'Employee Engagement',
                    'desc'    => 'Structured weekend cricket creates inter-department bonding, morale, retention stories and pride across offices.',
                  ],
                  [
                    'icon'    => '📢',
                    'tag'     => 'EMPLOYER BRAND',
                    'title'   => 'Corporate Branding &amp; PR',
                    'desc'    => 'Jersey presence, match graphics, player cards, leadership stories and highlight-led LinkedIn visibility.',
                  ],
                  [
                    'icon'    => '💪',
                    'tag'     => 'CSR + WELLNESS',
                    'title'   => 'Fitness &amp; Wellness Alignment',
                    'desc'    => 'Promote work-life balance through a credible sports platform backed by AI eligibility and structured formats.',
                  ],
                ];
                foreach ($benefitCards as $idx => $bc):
                  $isLast = ($idx === count($benefitCards) - 1);
                ?>

                <td width="33%" valign="top" style="padding:<?= $isLast ? '0' : '0 10px 0 0' ?>;">
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                        style="background-color:#ffffff;border:1.5px solid #dde3ee;border-radius:16px;overflow:hidden;height:100%;">
                    <tr>
                      <td style="padding:22px 20px 24px;vertical-align:top;">

                        <!-- Icon Circle -->
                        <div style="width:48px;height:48px;background-color:#eef2fb;border-radius:50%;text-align:center;line-height:48px;font-size:22px;margin-bottom:16px;">
                          <?= $bc['icon'] ?>
                        </div>

                        <!-- Tag pill -->
                        <div style="display:inline-block;border:1.5px solid #c7d5f0;border-radius:50px;padding:4px 12px;font-family:Arial,Helvetica,sans-serif;font-size:9px;font-weight:700;color:#1d56d9;letter-spacing:1px;text-transform:uppercase;margin-bottom:14px;">
                          <?= $bc['tag'] ?>
                        </div>

                        <!-- Title -->
                        <div style="font-family:Georgia,'Times New Roman',serif;font-size:15px;font-weight:700;color:#04122b;margin-bottom:10px;line-height:1.3;">
                          <?= $bc['title'] ?>
                        </div>

                        <!-- Description -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#4a5568;line-height:1.7;">
                          <?= $bc['desc'] ?>
                        </div>

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

                <?php endforeach; ?>

              </tr>
            </table>

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

    </td>
  </tr>
  <!-- ══ END CORPORATE BENEFITS ══ -->


  <!-- ══════════════════════════════════════════ PCL AI SPORTS TECH INITIATIVE ══════════════════════════════════════════ -->
  <tr>
    <td style="padding:28px 28px 0;">

      <!-- OUTER CARD with rounded border + blue top accent -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
            style="border:2px solid #dde3ee;border-radius:20px;overflow:hidden;background-color:#f8fafd;">

        <!-- Blue top accent bar -->
        <!-- <tr><td height="6" style="background:linear-gradient(90deg,#0b2c6b 0%,#1d56d9 100%);line-height:6px;font-size:6px;">&nbsp;</td></tr> -->

        <tr>
          <td style="padding:32px 28px 32px;">

            <!-- Section Label -->
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:700;color:#d7af59;letter-spacing:2px;text-transform:uppercase;margin-bottom:12px;">
              PCL AI Sports Tech Initiative
            </div>

            <!-- Headline -->
            <div style="font-family:Georgia,'Times New Roman',serif;font-size:26px;font-weight:700;color:#04122b;line-height:1.25;margin-bottom:14px;">
              One sports-tech solution for athlete intelligence, cricket AI and live match innovation.
            </div>

            <!-- Sub-text -->
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:13px;color:#64748b;line-height:1.7;margin-bottom:28px;">
              PCL AI Sports Tech Initiative connects athlete video analysis, fitness and movement grading, cricket skill intelligence, speed analysis, ball tracking, review logic and live match graphics into one premium platform.
            </div>

            <?php
            $techCards = [
              [
                'icon'  => '🎥',
                'title' => 'Video to Verdict',
                'desc'  => 'Athletes submit raw videos. PCL AI converts them into scores, improvement signals and a shareable report card.',
              ],
              [
                'icon'  => '🏃',
                'title' => '8 Fitness Modules',
                'desc'  => 'Speed, agility, balance, reaction, power, endurance, movement and cricket skill are graded inside one card.',
              ],
              [
                'icon'  => '🏏',
                'title' => 'Cricket Intelligence',
                'desc'  => 'Bowling action, run-up, release rhythm, batting movement and fielding readiness can be mapped to match performance.',
              ],
              [
                'icon'  => '📊',
                'title' => 'Team &amp; Corporate ROI',
                'desc'  => 'Corporate teams get measurable player readiness, squad depth signals and selection transparency.',
              ],
              [
                'icon'  => '📺',
                'title' => 'Broadcast Graphics',
                'desc'  => 'Speed analysis, ball tracking, impact visuals, win predictor and AI review graphics for PCL live matches.',
              ],
              [
                'icon'  => '👨‍👩‍👧',
                'title' => 'Kids &amp; Families',
                'desc'  => 'Useful for people who do not have time for trainers or structured coaching but want guided improvement.',
              ],
            ];
            ?>

            <!-- Row 1: Cards 1-3 -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:12px;">
              <tr>
                <?php foreach (array_slice($techCards, 0, 3) as $idx => $tc): ?>
                <td width="33%" valign="top" style="padding:<?= $idx < 2 ? '0 10px 0 0' : '0' ?>;">
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                        style="background-color:#ffffff;border:1.5px solid #dde3ee;border-radius:16px;overflow:hidden;">
                    <tr>
                      <td style="padding:20px 18px 22px;vertical-align:top;">

                        <!-- Icon Circle -->
                        <div style="width:48px;height:48px;background-color:#fdf8ec;border-radius:12px;text-align:center;line-height:48px;font-size:22px;margin-bottom:16px;">
                          <?= $tc['icon'] ?>
                        </div>

                        <!-- Title -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;font-weight:700;color:#04122b;margin-bottom:10px;line-height:1.3;">
                          <?= $tc['title'] ?>
                        </div>

                        <!-- Description -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#4a5568;line-height:1.7;">
                          <?= $tc['desc'] ?>
                        </div>

                      </td>
                    </tr>
                  </table>
                </td>
                <?php endforeach; ?>
              </tr>
            </table>

            <!-- Row 2: Cards 4-6 -->
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <?php foreach (array_slice($techCards, 3, 3) as $idx => $tc): ?>
                <td width="33%" valign="top" style="padding:<?= $idx < 2 ? '0 10px 0 0' : '0' ?>;">
                  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
                        style="background-color:#ffffff;border:1.5px solid #dde3ee;border-radius:16px;overflow:hidden;">
                    <tr>
                      <td style="padding:20px 18px 22px;vertical-align:top;">

                        <!-- Icon Circle -->
                        <div style="width:48px;height:48px;background-color:#fdf8ec;border-radius:12px;text-align:center;line-height:48px;font-size:22px;margin-bottom:16px;">
                          <?= $tc['icon'] ?>
                        </div>

                        <!-- Title -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;font-weight:700;color:#04122b;margin-bottom:10px;line-height:1.3;">
                          <?= $tc['title'] ?>
                        </div>

                        <!-- Description -->
                        <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#4a5568;line-height:1.7;">
                          <?= $tc['desc'] ?>
                        </div>

                      </td>
                    </tr>
                  </table>
                </td>
                <?php endforeach; ?>
              </tr>
            </table>

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

    </td>
  </tr>
  <!-- ══ END PCL AI SPORTS TECH ══ -->

  <!-- Ruhi New End -->


  <!-- ══════════════════════════════════════════CTA + WHATSAPP══════════════════════════════════════════ -->
  <tr>
    <td style="padding:24px 28px 0;">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:16px;">
        <tr>
          <td align="center" style="padding:4px 0;">
            <a href="https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile_new.php?lead_id=20001&team_id=<?= $teamIdParam ?>&team_name=<?= urlencode($teamName) ?>&source=email"
              style="display:inline-block;background-color:#d7af59;color:#04122b;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:14px;font-weight:700;padding:15px 40px;letter-spacing:0.5px;">
              View AI Dashboard &rarr;
            </a>
          </td>
        </tr>
        <tr>
          <td align="center" style="font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#7a5500;font-weight:700;padding-top:8px;letter-spacing:0.3px;">
            Limited slots per city &bull; First-come, first-serve basis
          </td>
        </tr>
      </table>
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f0fdf4;border:1px solid #bbf7d0;margin-bottom:0;">
        <tr>
          <td align="center" style="padding:20px;">
            <div style="font-family:Georgia,'Times New Roman',serif;font-size:15px;color:#14532d;font-weight:700;margin-bottom:12px;">Need help with next steps?</div>
            <a href="https://wa.me/919999999999"
              style="display:inline-block;background-color:#16a34a;color:#ffffff;text-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:13px;font-weight:700;padding:12px 28px;letter-spacing:0.3px;">
              Talk to PCL Support on WhatsApp
            </a>
          </td>
        </tr>
      </table>
    </td>
  </tr>
  <!-- ══ END CTA ══ -->


  <!-- ══════════════════════════════════════════PCL STATS BANNER══════════════════════════════════════════ -->
  <tr>
    <td style="padding:24px 28px 0;">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#113B93;">
        <tr>
          <td style="padding:20px 10px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <?php
                $pclGlobalStats = [
                  ['val'=>number_format((int)$statsArrayData['total_matches_played']),'lbl'=>'Matches'],
                  ['val'=>number_format((int)$statsArrayData['total_runs_Scored']),'lbl'=>'Runs'],
                  ['val'=>number_format((int)$statsArrayData['total_wickets_Claimed']),'lbl'=>'Wickets'],
                  ['val'=>number_format((int)$statsArrayData['total_hundreds']),'lbl'=>'Hundreds'],
                  ['val'=>number_format((int)$statsArrayData['total_fifties']),'lbl'=>'Fifties'],
                ];
                $lastIdx = count($pclGlobalStats) - 1;
                foreach ($pclGlobalStats as $idx => $gs):
                ?>
                <td align="center" width="20%" style="padding:6px 4px;<?= $idx < $lastIdx ? 'border-right:1px solid rgba(255,255,255,0.1);' : '' ?>">
                  <div style="font-family:Georgia,'Times New Roman',serif;font-size:20px;font-weight:700;color:#d7af59;line-height:1.1;"><?= $gs['val'] ?></div>
                  <div style="font-family:Arial,Helvetica,sans-serif;font-size:9px;color:#fff;text-transform:uppercase;letter-spacing:1px;margin-top:5px;"><?= $gs['lbl'] ?></div>
                </td>
                <?php endforeach; ?>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </td>
  </tr>
  <!-- ══ END STATS BANNER ══ -->


  <!-- ══════════════════════════════════════════CHAMPIONS SECTION══════════════════════════════════════════ -->
  <tr>
    <td style="padding:28px 28px 0;">
      <div style="font-family:Georgia,'Times New Roman',serif;font-size:17px;font-weight:700;color:#04122b;margin-bottom:4px;border-bottom:2px solid #d7af59;padding-bottom:10px;">Chris Gayle #TheUniverseBoss &times; PCL</div>
      <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#64748b;text-transform:uppercase;letter-spacing:1px;margin-bottom:16px;margin-top:4px;">Year 2026 Corporate Champions</div>
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <?php
          $champions = [
            ['img'=>'jr_image_1.jpeg','name'=>'HCL Tech','cat'=>'IT &amp; Services (Platinum)'],
            ['img'=>'jr_image_2.jpeg','name'=>'Siemens','cat'=>'IT &amp; Services (Diamond)'],
            ['img'=>'jr_image_3.jpeg','name'=>'Sopra Banking','cat'=>'IT &amp; Services (Platinum)'],
            ['img'=>'jr_image_4.jpeg','name'=>'KEI Wires &amp; Cables','cat'=>'Corporate'],
          ];
          foreach ($champions as $c):
          ?>
          <td width="25%" align="center" style="padding:0 5px;">
            <div style="border:1px solid #e2e8f0;overflow:hidden;margin-bottom:8px;">
              <img src="<?= $filePath . $c['img'] . '?v=' . $imgVersion ?>" width="138" height="104" style="display:block;width:100%;object-fit:cover;border:0;" alt="<?= $c['name'] ?>">
            </div>
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:700;color:#04122b;line-height:1.4;"><?= $c['name'] ?></div>
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:10px;color:#64748b;margin-top:2px;"><?= $c['cat'] ?></div>
          </td>
          <?php endforeach; ?>
        </tr>
      </table>
    </td>
  </tr>

  <tr>
    <td style="padding:24px 28px 0;">
      <div style="font-family:Georgia,'Times New Roman',serif;font-size:17px;font-weight:700;color:#04122b;margin-bottom:4px;border-bottom:2px solid #0d2a5e;padding-bottom:10px;">Year 2026 Corporate Challengers</div>
      <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#64748b;text-transform:uppercase;letter-spacing:1px;margin-bottom:16px;margin-top:4px;">Competing for the Crown</div>
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <?php
          $challengers = [
            ['img'=>'jr_image_5.jpeg','name'=>'COFORGE Gurugram','cat'=>'IT &amp; Services (Platinum)'],
            ['img'=>'jr_image_6.jpeg','name'=>'COFORGE Noida','cat'=>'IT &amp; Services (Diamond)'],
            ['img'=>'jr_image_7.jpeg','name'=>'IFFCO','cat'=>'IT &amp; Services (Platinum)'],
            ['img'=>'jr_image_8.jpeg','name'=>'SPARK MINDA','cat'=>'Corporate'],
          ];
          foreach ($challengers as $c):
          ?>
          <td width="25%" align="center" style="padding:0 5px;">
            <div style="border:1px solid #e2e8f0;overflow:hidden;margin-bottom:8px;">
              <img src="<?= $filePath . $c['img'] . '?v=' . $imgVersion ?>" width="138" height="104" style="display:block;width:100%;object-fit:cover;border:0;" alt="<?= $c['name'] ?>">
            </div>
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:700;color:#04122b;line-height:1.4;"><?= $c['name'] ?></div>
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:10px;color:#64748b;margin-top:2px;"><?= $c['cat'] ?></div>
          </td>
          <?php endforeach; ?>
        </tr>
      </table>
    </td>
  </tr>

  <tr>
    <td style="padding:24px 28px 0;">
      <div style="font-family:Georgia,'Times New Roman',serif;font-size:17px;font-weight:700;color:#04122b;margin-bottom:4px;border-bottom:2px solid #d7af59;padding-bottom:10px;">Jonty Rhodes &times; PCL 2025</div>
      <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#64748b;text-transform:uppercase;letter-spacing:1px;margin-bottom:16px;margin-top:4px;">Champions &amp; Awards Ceremony</div>
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <?php
          $jonty = [
            ['img'=>'jr_image_9.jpeg','name'=>'TCS','cat'=>'Tata Consultancy Services'],
            ['img'=>'jr_image_10.jpeg','name'=>'Teleperformance','cat'=>'Corporate Champion'],
            ['img'=>'jr_image_11.jpeg','name'=>'Optum Noida','cat'=>'Healthcare Leader'],
            ['img'=>'jr_image_12.jpeg','name'=>'Team Avengers','cat'=>'Corporate Champion'],
          ];
          foreach ($jonty as $c):
          ?>
          <td width="25%" align="center" style="padding:0 5px;">
            <div style="border:1px solid #e2e8f0;overflow:hidden;margin-bottom:8px;">
              <img src="<?= $filePath . $c['img'] . '?v=' . $imgVersion ?>" width="138" height="104" style="display:block;width:100%;object-fit:cover;border:0;" alt="<?= $c['name'] ?>">
            </div>
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:700;color:#04122b;line-height:1.4;"><?= $c['name'] ?></div>
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:10px;color:#64748b;margin-top:2px;"><?= $c['cat'] ?></div>
          </td>
          <?php endforeach; ?>
        </tr>
      </table>
    </td>
  </tr>
  <!-- ══ END CHAMPIONS ══ -->


  <!-- ══════════════════════════════════════════FOOTER══════════════════════════════════════════ -->
  <tr>
    <td style="padding:0;">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:28px;">
        <tr><td style="height:3px;background-color:#d7af59;font-size:0;line-height:0;">&nbsp;</td></tr>
      </table>
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#0b2c6b;">
        <tr>
          <td align="center" style="padding:28px 24px;">
            <img 
              src="https://www.procorporateleague.com/2026/pcl/Imp_PCL_Logo_Black.png"
              alt="PCL"
              style="
                width:60px;
                height:auto;
                max-width:60px;
                display:block;
                margin:0 auto 14px;
                border:0;
              "
            >
            <div style="font-family:Georgia,'Times New Roman',serif;font-size:16px;font-weight:700;color:#d7af59;margin-bottom:6px;">Pro Corporate League</div>
            <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;color:#fff;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:20px;">India's Largest Corporate Cricket Ecosystem</div>
            <img src="https://wplspeedqueen.com/email_api/qrPCL.jpeg" alt="Scan QR Code" width="72" height="72"
              style="display:block;margin:0 auto 16px;border:2px solid #d7af59;">
            <a href="https://www.procorporateleague.com" style="font-family:Arial,Helvetica,sans-serif;font-size:12px;color:#d7af59;text-decoration:none;font-weight:700;letter-spacing:0.5px;">www.procorporateleague.com</a>
            
            <div style="margin-top:20px;padding-top:16px;border-top:1px solid rgba(255,255,255,0.07);font-family:Arial,Helvetica,sans-serif;font-size:10px;color:#fff;line-height:1.6;">
              &copy; <?= $year ?> Pro Corporate League. All rights reserved.<br>

              This communication was generated as part of the PCL Corporate Qualification Intelligence Program 2026.
              <br>
              Pro Corporate League<br>
              India’s Largest Corporate Cricket Ecosystem
            </div>
          </td>
        </tr>
      </table>
    </td>
  </tr>
  <!-- ══ END FOOTER ══ -->

</table>
<!--[if (gte mso 9)|(IE)]>
</td></tr></table>
<![endif]-->

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

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


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

$ccList = $requestData['cc'] ?? [];

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->CharSet  = 'UTF-8';
    $mail->Encoding = 'base64';

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

    $mail->addAddress($email, htmlspecialchars($toName));
    //$mail->addAddress('mohammad.mozammil@procorporateleague.com', 'Mozammil');
    
    if (!empty($ccList) && is_array($ccList))
    {
        foreach ($ccList as $cc)
        {
            $ccEmail = trim($cc['email'] ?? '');
            $ccName  = trim($cc['name']  ?? '');

            if (!empty($ccEmail))
            {
                $mail->addCC($ccEmail, $ccName);
            }
        }
    }
    else{
      $mail->addCC('sachin.gupta@procorporateleague.com', 'Sachin Gupta');
      $mail->addCC('rifat.saleem@procorporateleague.com', 'Rifat Saleem');
    }

    $mail->isHTML(true);
    $mail->Subject = !empty($requestData['subject']) ? $requestData['subject'] : 'PCL Team AI Report Card';
    $mail->Body    = $emailBody;

    $mail->send();

    echo json_encode([
        "status_code" => 200,
        "status"      => "success",
        "message"     => "Email sent successfully"
    ]);

} catch (Exception $e) {
    echo json_encode([
        "status_code" => 500,
        "status"      => "error",
        "message"     => $mail->ErrorInfo
    ]);
}
?>