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

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

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

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

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

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

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

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

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

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

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

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

/* ===============================
   LIVE AI REPORT CARD DATA
   Same source used on playerDashboard.php
================================ */
$aiApi = pcl_api_get('https://www.procorporateleague.com/pcl_rest/api/v9/lead/getAIReportCard/' . rawurlencode($leadRequestId));
$aiRow = [];
if (!empty($aiApi['data']['results'][0]) && is_array($aiApi['data']['results'][0])) {
    $aiRow = $aiApi['data']['results'][0];
}

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

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

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

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

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

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

$trophyImage = 'https://wplspeedqueen.com/email_api/cwctrophy.png';
$pclLogo = 'https://www.procorporateleague.com/2026/pcl/Imp_PCL_Logo_Black.png';
$sonyLivLogo = 'https://www.procorporateleague.com/2026/pcl/SonyLIV_2020.png';
$cwcHeroImage = 'https://www.roadtocorporateworldcup.com/assets/corporateworldcup.jpeg';
$firechatImage = 'https://wplspeedqueen.com/email_api/firechat.png';
$merchandiseImage = 'https://wplspeedqueen.com/email_api/cwcmerchandise.jpeg';

$safeName = pcl_safe($userName);
$safeCity = pcl_safe($city);
$safeRegistrationType = pcl_safe($registrationType);
$safeCompany = pcl_safe($companyName ?: 'Corporate Professional');
$safeScore = pcl_safe($aiScore ?: 'Generated');
$safeGrade = pcl_safe($aiGrade ?: 'AI Rated');
$safePlayerType = pcl_safe($playerType);
$safeSelectionProbability = pcl_safe($selectionProbability);
$safeSelectionBand = pcl_safe($selectionBand);
$safeMobile = pcl_safe($mobile);
$safeLeadId = pcl_safe($leadRequestId);
$safeTotal = pcl_safe(pcl_money($totalAmount));
$safePayment = pcl_safe(pcl_money($paymentAmount));
$safeGst = pcl_safe(pcl_money($gst));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

$subject = trim((string)($requestData['subject'] ?? ''));
if ($subject === '') {
    $subject = 'Reminder: Your PCL AI Report Card Is Ready — Confirm Challenger Round Participation';
}

/* ===============================
   SEND EMAIL
================================ */
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host       = $smtpRow['smtp_host'] ?? '';
    $mail->SMTPAuth   = true;
    $mail->Username   = $smtpRow['smtp_username'] ?? '';
    $mail->Password   = $smtpRow['smtp_password'] ?? '';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;
    $mail->Timeout    = 15;
    $mail->SMTPKeepAlive = true;

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

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

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

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

    echo json_encode([
        "status_code" => 200,
        "status" => "success",
        "message" => "Premium PCL Challenger Round payment reminder sent successfully",
        "lead_id" => $leadRequestId,
        "email" => $email,
        "ai_score" => $aiScore,
        "ai_grade" => $aiGrade
    ]);
} catch (Exception $e) {
    echo json_encode([
        "status_code" => 500,
        "status" => "error",
        "message" => $mail->ErrorInfo
    ]);
}
