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

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

/* ===============================
   ENTERPRISE EMAIL LOGGING CLIENT
   Dynamic mapping: email file sends runtime facts only.
   Controller resolves module/submodule/source from DB using active_file_name/server path/URLs.
================================ */

$data = json_decode(file_get_contents("php://input"), true);
// echo "<pre>"; print_r($data);
// die;


$postData = [
    "subject"                   =>  ucwords($data['team_name']).' 🏆 Registration Confirmed | Your Road to the Corporate World Cup™ Begins' ?? 'Test Email',
    "email"                     => $data['email']              ?? '',
    "name"                      => $data['full_name']          ?? 'PCL',
    "city"                      => $data['city']               ?? '',
    "reference_id"              => $data['reference_id']       ?? '',
    "registration_type"         => $data['registration_type']  ?? '',
    "mobile"                    => $data['mobile']             ?? '',
    "user_id"                   => $data['userId']             ?? '',
    "company_name"              => $data['company_name']       ?? '',
    "team_name"                 => $data['team_name']          ?? '',
    "person_name"               => $data['person_name']        ?? '',
    "team_type"                 => $data['team_type']          ?? '',
    "sector"                    => $data['corporate_sector']             ?? '',
    "availability_window"       => $data['availability_window'] ?? ''
];

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

// die;
$__pclEmailTrackingClient = __DIR__ . '/EmailTrackingApiClient.php';
if (file_exists($__pclEmailTrackingClient)) {
    require_once $__pclEmailTrackingClient;
}

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

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

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

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

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

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

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

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

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

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

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

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

        $payload = [
            // Runtime recipient/data facts only. No module_key/submodule_key hardcoding here.
            'lead_id'            => $leadId,
            'team_id'            => $extra['team_id'] ?? $postData['team_id'] ?? $postData['teamId'] ?? '',
            'user_id'            => $extra['user_id'] ?? $postData['user_id'] ?? $postData['userId'] ?? '',

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

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

            // Final rendered client email after all dynamic replacements.
            'full_email_html'    => $html,
            'full_email_text'    => pcl_email_flatten_text($html),

            // Attachments / linked docs.
            'attachment_urls'    => implode(',', $attachmentUrls),
            'attachments_json'   => json_encode($attachmentUrls, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'attachment_count'   => count($attachmentUrls),

            // URL/file audit. Values are runtime-derived, not business hardcoded.
            'current_email_url'  => pcl_email_runtime_url(),
            'public_calling_url' => pcl_email_runtime_url(),
            'calling_file_url'   => $extra['calling_file_url'] ?? $postData['calling_file_url'] ?? $requestPayload['calling_file_url'] ?? ($_SERVER['HTTP_REFERER'] ?? null),
            'calling_page_url'   => $extra['calling_page_url'] ?? $postData['calling_page_url'] ?? $requestPayload['calling_page_url'] ?? ($_SERVER['HTTP_REFERER'] ?? null),
            'direct_email_url'   => pcl_email_public_file_url(),
            'server_full_path'   => __FILE__,
            'server_file_path'   => __FILE__,
            'script_name'        => basename(__FILE__),
            'active_file_name'   => basename(__FILE__),
            'request_uri'        => $_SERVER['REQUEST_URI'] ?? null,

            // Delivery/provider info.
            'status'             => $status,
            'delivery_status'    => $deliveryStatus,
            'provider_message_id'=> $messageId,
            'error_message'      => $extra['error_message'] ?? null,

            // Request/response audit.
            'request_payload_json' => $requestPayload,
            'response_json'        => $extra['response_json'] ?? [
                'status' => $status,
                'message' => $extra['message'] ?? null,
                'provider_message_id' => $messageId,
            ],
        ];

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







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

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

/* ===============================
   BUILD TEMPLATE VARIABLES
================================ */
$user_name         = htmlspecialchars($postData['name']);
$user_email        = htmlspecialchars($postData['email']);
$city              = htmlspecialchars($postData['city']);
$reference_id      = htmlspecialchars($postData['reference_id']);
$registration_type = htmlspecialchars($postData['registration_type']);
$user_mobile       = htmlspecialchars($postData['mobile']);
$cta_link          = "https://www.procorporateleague.com/2026/pcl/eleven11.php?lead_id=" . urlencode($postData['reference_id']) . "&id=" . urlencode($postData['user_id']);
$availability_window = htmlspecialchars($postData['availability_window']);

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

/* ===============================
   FETCH 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        => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => 'GET',
]);
$statsresponse = curl_exec($statscurl);
curl_close($statscurl);

$getstatsresponse = json_decode($statsresponse, true);
$statsArrayData = [
    'total_matches_played'  => $getstatsresponse['results'][0]['Total_Matches_Played']  ?? '',
    'total_runs_Scored'     => $getstatsresponse['results'][0]['Total_Runs_Scored']     ?? '',
    'total_wickets_Claimed' => $getstatsresponse['results'][0]['Total_Wickets_Claimed'] ?? '',
    'total_hundreds'        => $getstatsresponse['results'][0]['Total_Hundreds']        ?? '',
    'total_fifties'         => $getstatsresponse['results'][0]['Total_Fifties']         ?? '',
];

$team_type  = htmlspecialchars($postData['team_type']);
$team_name = htmlspecialchars($postData['team_name']);

// echo "<pre>"; print_r($city); die;
if (strcasecmp(trim($city), 'Mumbai') === 0) {
    $advanceAmount = 74000;
} else {
    $advanceAmount = 50000;
}




// getCities Curl Start
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://www.procorporateleague.com/pcl_rest/api/v9/corporate/getAllCities',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);
curl_close($curl);

$data = json_decode($response, true);
// echo "<pre>"; print_r($data); die;


$city_id = $postData['city']??'';

$city = '';

if (!empty($data['results'])) {
    foreach ($data['results'] as $row) {
        if ($row['city_name'] == $city_id) {
            $city = $row['city_name'];
            break;
        }
    }
}
// End




// getSector Curl Start
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://www.procorporateleague.com/pcl_rest/api/v9/corporate/getAllSectors',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);
curl_close($curl);

$data = json_decode($response, true);
// echo "<pre>"; print_r($data); die;


$sector_id = $postData['sector']??'';

// echo $sector_id; die;

$sector = '';

if (!empty($data['results'])) {
    foreach ($data['results'] as $row) {
        if ($row['sector_name'] == $sector_id) {
            $sector = $row['sector_name'];
            break;
        }
    }
}
// End

//echo $sector; die;

/* ===============================EMAIL TEMPLATE================================ */
ob_start();
?>

<!DOCTYPE html>
<html>
<head>
    <style>
        .confirm-section { margin: 20px 0; }
        .confirm-title {
            font-size: 10px; color: #8899aa; text-transform: uppercase;
            letter-spacing: 2px; font-weight: 700; margin: 0 0 14px;
        }
    </style>
</head>
<body style="margin:0;background:#f4f7fb;font-family:Arial, sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="padding:15px;">
    <tr>
        <td align="center">
            <table width="100%" cellpadding="0" cellspacing="0" style="max-width:720px;background:#ffffff;border-radius:10px;overflow:hidden;">

                <!-- HEADER -->
                <tr>
                    <td style="background:#123a8c;padding:20px;">
                        <table width="100%" cellpadding="0" cellspacing="0" border="0">
                            <tr>
                                <td width="130" valign="middle" align="left">
                                    <img src="https://wplspeedqueen.com/email_api/cwctrophy1.png"
                                        width="100"
                                        alt="Trophy"
                                        style="display:block;">
                                </td>

                                <td align="center" valign="middle">
                                    <img src="https://www.procorporateleague.com/2026/pcl/Imp_PCL_Logo_Black.png"
                                        width="110"
                                        alt="PCL Logo"
                                        style="display:block;margin:0 auto 8px;">

                                    <p style="color:#dbe7ff;font-size:12px;line-height:25px;margin:0;">
                                        Welcome to the <strong>#CorporateWorldCup</strong> journey<br>
                                        Only 8 Team Slots per City
                                    </p>
                                </td>

                                <td width="120">&nbsp;</td>
                            </tr>
                        </table>
                    </td>
                </tr>

                

                <!-- CONTENT -->
                <tr>
                    <td style="padding:20px;">
                        <p style="font-size:15px;">Dear <strong><?= ucwords($person_name) ?></strong>,</p>
                        <p style="font-size:15px;">Thank you for registering with <strong>Pro Corporate League (PCL)</strong> – India's Largest Corporate Cricket Ecosystem.</p>
                        <p style="font-size:15px;">Your registration has been <strong>successfully completed</strong>, and you are now officially part of the PCL journey.</p>

                        <?php if ($team_type  == 'Reserved') { ?>
                            <!-- ==================== RESERVATION SECTION ==================== -->
                            <table width="100%" cellpadding="0" cellspacing="0" style="margin:25px 0;">
                                <tr>
                                    <td style="background:#f5f5f5;border-radius:10px;padding:25px;">
                                        <h2 style="margin:0;color:#333;font-size:29px;font-weight:bold;">
                                            🎉 Congratulations !
                                        </h2>

                                        <p style="font-size:16px;line-height:28px;color:#333;margin-top:20px;">
                                            Your corporate team's slot has been successfully
                                            <strong>reserved for 72 hours.</strong>
                                        </p>

                                        <table width="100%" cellpadding="0" cellspacing="0"
                                            style="background:#efe4d2;border-left:6px solid #0e2d6b;margin-top:20px;">
                                            <tr>
                                                <td style="padding:18px;">
                                                    <p style="margin:8px 0;"><strong>City:</strong> <?= $city ?? '' ?></p>
                                                    <p style="margin:8px 0;"><strong>Team Name:</strong> <?= $team_name ?? '' ?></p>
                                                    <p style="margin:8px 0;"><strong>Advance Amount:</strong> ₹<?= number_format(50000?? 0) ?></p>
                                                </td>
                                            </tr>
                                        </table>

                                        <h2 style="margin-top:35px;color:#333;">
                                            ⏰ Reservation Timer:
                                        </h2>

                                        <table width="100%" cellpadding="0" cellspacing="0"
                                            style="background:#ededed;border-radius:12px;">
                                            <tr>
                                                <td align="center"
                                                    style="padding:35px;font-size:42px;font-weight:bold;color:#d9480f;">
                                                    72 Hours
                                                </td>
                                            </tr>
                                        </table>

                                         <!-- dashboard button -->
                                    <table align="center" cellpadding="0" cellspacing="0" style="margin:35px auto;">
                                        <tr>
                                            <td bgcolor="#0e2d6b" style="border-radius:10px;">
                                                <a href=" https://www.procorporateleague.com/pcl/team-register/pcl-team-dashboard.php?mobile=<?php echo urlencode($user_mobile ); ?>&lead_id=<?php echo urlencode($reference_id); ?>"
                                                style="display:inline-block;padding:18px 40px;color:#fff;text-decoration:none;font-size:18px;font-weight:bold;">
                                                    Dashboard →
                                                </a>
                                            </td>
                                        </tr>
                                    </table>

                                    <!-- end -->

                                        

                                        <!-- <table align="center" cellpadding="0" cellspacing="0" style="margin:35px auto;">
                                            <tr>
                                               <td bgcolor="#0e2d6b" style="border-radius:10px;">
                                                    <a href=" https://www.procorporateleague.com/pcl/team-register/teamInvoice.php?mobile=<//?php echo urlencode($user_mobile ); ?>&lead_id=<//?php echo urlencode($reference_id); ?>&amount=<//?php echo $advanceAmount; ?>"
                                                    style="display:inline-block;padding:18px 40px;color:#fff;text-decoration:none;font-size:18px;font-weight:bold;">
                                                        Complete Payment Now →
                                                    </a>
                                                </td>
                                            </tr>
                                        </table> -->

                                        <p style="font-size:16px;line-height:28px;color:#444;">
                                            If you do not complete the payment within 72 hours,
                                            your slot will be released automatically and made available for other teams.
                                        </p>
                                    </td>
                                </tr>
                            </table>
                            <!-- ==================== RESERVATION SECTION END ==================== -->
                            <!-- callback section start -->
                        <?php } elseif ($team_type == 'Callback') { ?>

                         <table width="100%" cellpadding="0" cellspacing="0" style="margin:25px 0;">
                            <tr>
                                <td style="background:#f5f5f5;border-radius:10px;padding:25px;">
                                    <h2 style="margin:0;color:#333;font-size:22px;font-weight:bold;">
                                        📞 Callback Successfully Arranged!
                                    </h2>

                                    <p style="font-size:16px;line-height:28px;color:#333;margin-top:20px;">
                                        Your callback request has been <strong>successfully registered.</strong>
                                        Our team will contact you at your scheduled time.
                                    </p>

                                    <table width="100%" cellpadding="0" cellspacing="0"
                                        style="background:#efe4d2;border-left:6px solid #0e2d6b;margin-top:20px;">
                                        <tr>
                                            <td style="padding:18px;">
                                                <p style="margin:8px 0;"><strong>City:</strong> <?= $city ?? '' ?></p>
                                                <p style="margin:8px 0;"><strong>Team Name:</strong> <?= $team_name ?? '' ?></p>
                                                <p style="margin:8px 0;"><strong>Callback Slot:</strong> <?= $availability_window ?? '' ?></p>
                                            </td>
                                        </tr>
                                    </table>

                                    <!-- dashboard button -->
                                    <table align="center" cellpadding="0" cellspacing="0" style="margin:35px auto;">
                                        <tr>
                                            <td bgcolor="#0e2d6b" style="border-radius:10px;">
                                                <a href=" https://www.procorporateleague.com/pcl/team-register/pcl-team-dashboard.php?mobile=<?php echo urlencode($user_mobile ); ?>&lead_id=<?php echo urlencode($reference_id); ?>"
                                                style="display:inline-block;padding:18px 40px;color:#fff;text-decoration:none;font-size:18px;font-weight:bold;">
                                                    Dashboard →
                                                </a>
                                            </td>
                                        </tr>
                                    </table>

                                    <!-- end -->

                                    <h2 style="margin-top:35px;color:#333;">
                                        ⏰ Your Scheduled Callback:
                                    </h2>

                                    

                                    <table width="100%" cellpadding="0" cellspacing="0"
                                        style="background:#ededed;border-radius:12px;">
                                        <tr>
                                            <td align="center"
                                                style="padding:35px;font-size:24px;font-weight:bold;color:#0e2d6b;">
                                                <?= $availability_window ?? '' ?>
                                            </td>
                                        </tr>
                                    </table>

                                    <table width="100%" cellpadding="0" cellspacing="0"
                                        style="background:#fff8ec;border-left:6px solid #f59e0b;border-radius:6px;margin-top:25px;">
                                        <tr>
                                            <td style="padding:18px;">
                                                <p style="margin:0;font-size:15px;line-height:26px;color:#92400e;">
                                                    📌 <strong>Note:</strong> Our PCL representative will call you during your selected time slot.
                                                    Please keep your phone reachable. If you miss the call, we will try once more.
                                                </p>
                                            </td>
                                        </tr>
                                    </table>

                                   

                                    <p style="font-size:16px;line-height:28px;color:#444;margin-top:25px;">
                                        Meanwhile, you can explore more about the Pro Corporate League and prepare your team details.
                                    </p>
                                </td>
                            </tr>
                        </table>

                        <!-- end callback section -->

                        <?php } else { ?>

                            <!-- confirm payment section start -->
                            <table width="100%" cellpadding="0" cellspacing="0" style="margin-top:20px;">
                                <tr>
                                    <td style="background:#f8f8f8;border-radius:10px;padding:25px;">

                                        <h2 style="margin:0 0 15px;color:#198754;">
                                            ✅ Your Slot is Confirmed!
                                        </h2>

                                        <p style="font-size:16px;line-height:24px;">
                                            Thank you for registering with
                                            <strong>Pro Corporate League (PCL)</strong>.
                                            Your team slot has been
                                            <strong>successfully confirmed.</strong>
                                        </p>

                                        <table width="100%" cellpadding="0" cellspacing="0"
                                            style="background:#f3f8f4;border:1px solid #cfe8d6;border-radius:8px;margin-top:20px;">
                                            <tr>
                                                <td style="padding:18px;">

                                                    <h3 style="margin:0 0 10px;color:#198754;">
                                                        💳 Advance Payment 
                                                    </h3>

                                                    <p style="font-size:16px;margin:0;">
                                                        <strong>₹<?= number_format($advanceAmount ?? 0) ?></strong>
                                                        (10% Advance) Team slot confirmed. Advance payment is pending
                                                    </p>

                                                    <p style="margin-top:10px;color:#555;">
                                                        Remaining amount can be paid later
                                                        as per the schedule.
                                                    </p>

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

                                    </td>
                                </tr>
                            </table>
                            <!-- confirm payment end -->

                        <?php } ?>

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



                        <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> 
                       


                         <!-- NEXT STEPS -->
                        <h3 style="margin-top:15px;color:#0b1f4d;">What Happens Next?</h3>
                        <?php if (!empty($registration_type) && $registration_type == 'individual'): ?>
                            <p>✅ Our team will review your details</p>
                            <p>🎥 If applicable, your uploaded video will undergo AI-based evaluation</p>
                            <p>📩 You will receive further updates on your registered email / WhatsApp</p>
                            <p>🏏 Get ready for matches, trials & national broadcast opportunities</p>
                        <?php else: ?>
                            <p>✅ Our team will review your details</p>
                            <p>📩 You will receive further updates on your registered email / WhatsApp</p>
                            <p>🏏 Get ready for matches, trials & national broadcast opportunities</p>
                        <?php endif; ?>

                        

                        <!-- WHY PCL -->
                        <h3 style="color:#0b1f4d;">Why PCL (Pro Corporate League)?</h3>
                        <p>• 3000+ Matches | 140+ Corporates | 15+ Years Legacy</p>
                        <p>• Play, compete, and get noticed on India's premier corporate cricket ecosystem</p>
                        <p>We look forward to seeing you on the field.</p>
                        <p><strong>PCL Journey in Numbers (2011-2026)</strong></p>

                        <!-- STATS BANNER -->
                        <table width="100%" cellpadding="0" cellspacing="0">
                            <tr>
                                <td style="background:linear-gradient(135deg,#0e2d6b 0%,#112f70 100%);padding:16px 10px 18px;">
                                    <table width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td align="center" width="20%" style="border-right:1px solid rgba(255,255,255,0.12);padding:6px 4px;">
                                                <div style="font-size:22px;font-weight:700;color:#f5c842;line-height:1.1;letter-spacing:-0.5px;"><?= number_format($statsArrayData['total_matches_played'] ?: 0) ?></div>
                                                <div style="font-size:10px;color:#a8bfe8;text-transform:uppercase;letter-spacing:1px;margin-top:3px;">Matches</div>
                                            </td>
                                            <td align="center" width="20%" style="border-right:1px solid rgba(255,255,255,0.12);padding:6px 4px;">
                                                <div style="font-size:22px;font-weight:700;color:#f5c842;line-height:1.1;letter-spacing:-0.5px;"><?= number_format($statsArrayData['total_runs_Scored'] ?: 0) ?></div>
                                                <div style="font-size:10px;color:#a8bfe8;text-transform:uppercase;letter-spacing:1px;margin-top:3px;">Runs</div>
                                            </td>
                                            <td align="center" width="20%" style="border-right:1px solid rgba(255,255,255,0.12);padding:6px 4px;">
                                                <div style="font-size:22px;font-weight:700;color:#f5c842;line-height:1.1;letter-spacing:-0.5px;"><?= number_format($statsArrayData['total_wickets_Claimed'] ?: 0) ?></div>
                                                <div style="font-size:10px;color:#a8bfe8;text-transform:uppercase;letter-spacing:1px;margin-top:3px;">Wickets</div>
                                            </td>
                                            <td align="center" width="20%" style="border-right:1px solid rgba(255,255,255,0.12);padding:6px 4px;">
                                                <div style="font-size:22px;font-weight:700;color:#f5c842;line-height:1.1;letter-spacing:-0.5px;"><?= number_format($statsArrayData['total_hundreds'] ?: 0) ?></div>
                                                <div style="font-size:10px;color:#a8bfe8;text-transform:uppercase;letter-spacing:1px;margin-top:3px;">Hundreds</div>
                                            </td>
                                            <td align="center" width="20%" style="padding:6px 4px;">
                                                <div style="font-size:22px;font-weight:700;color:#f5c842;line-height:1.1;letter-spacing:-0.5px;"><?= number_format($statsArrayData['total_fifties'] ?: 0) ?></div>
                                                <div style="font-size:10px;color:#a8bfe8;text-transform:uppercase;letter-spacing:1px;margin-top:3px;">Fifties</div>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>

                        <!-- CHAMPIONS -->
                        <h3 style="margin-top:25px;margin-bottom:12px;color:#0b1f4d;">Chris Gayle #TheUniverseBoss x PCL - Year 2026 Corporate Champions</h3>
                        <table width="100%" cellpadding="0" cellspacing="0" style="margin:15px 0;">
                            <tr>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_1.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="HCL Tech Champion">
                                    <p>HCL Tech - IT & Services (Platinum Category)</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_2.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Champion 2">
                                    <p>Siemens - IT & Services (Diamond Category)</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_3.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Champion 3">
                                    <p>Sopra Banking - IT & Services (Platinum Category)</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_4.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Champion 4">
                                    <p>KEI Wires & Cables - Corporate Category</p>
                                </td>
                            </tr>
                        </table>

                        <!-- CHALLENGERS -->
                        <h3 style="margin-top:25px;margin-bottom:12px;color:#0b1f4d;">Year 2026 Corporate Challengers</h3>
                        <table width="100%" cellpadding="0" cellspacing="0" style="margin:15px 0;">
                            <tr>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_5.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Challenger 1">
                                    <p>COFORGE Gurugram - IT & Services (Platinum Category)</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_6.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Challenger 2">
                                    <p>COFORGE Noida - IT & Services (Diamond Category)</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_7.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Challenger 3">
                                    <p>IFFCO - IT & Services (Platinum Category)</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_8.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Challenger 4">
                                    <p>SPARK MINDA - Corporate Category</p>
                                </td>
                            </tr>
                        </table>

                        <!-- JONTY RHODES -->
                        <h3 style="margin-top:25px;margin-bottom:12px;color:#0b1f4d;">Jonty Rhodes x PCL 2025 – Champions & Awards Ceremony</h3>
                        <table width="100%" cellpadding="0" cellspacing="0" style="margin:15px 0;">
                            <tr>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_9.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Live Matches">
                                    <p>TCS (Tata Consultancy Services)</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_10.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Corporate Teams">
                                    <p>Teleperformance</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_11.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Sony LIV">
                                    <p>Optum Noida</p>
                                </td>
                                <td width="25%" align="center" style="padding:4px;">
                                    <img src="<?= $filePath . 'jr_image_12.jpeg?v=' . $imgVersion ?>" width="155" height="115" style="border-radius:8px;display:block;object-fit:cover;max-width:100%;" alt="Trophies">
                                    <p>Team Avengers</p>
                                </td>
                            </tr>
                        </table>

                        <!-- WHATSAPP -->
                        <div class="confirm-section" style="text-align:center;">
                            <div style="color:black;font-size:15px;margin-bottom:10px;">Need help? Talk to PCL Support on WhatsApp</div>
                            <a href="https://wa.me/919818596699?text=Hi%2C%20I%20have%20been%20shortlisted%20for%20the%20PCL%20Challenger%20Round.%20I%20have%20a%20few%20questions%20for%20next%20steps" target="_blank">
                                <img src="https://upload.wikimedia.org/wikipedia/commons/6/6b/WhatsApp.svg" alt="WhatsApp" width="32" style="display:inline-block;">
                            </a>
                            <div align="center" style="margin-top:10px;">
                                <img src="https://wplspeedqueen.com/email_api/qrPCL.jpeg" alt="PCL" width="200" height="200" style="margin-top:20px;display:block;margin-left:auto;margin-right:auto;">
                                <br>
                                <a href="https://www.procorporateleague.com" style="text-decoration:none;">https://www.procorporateleague.com</a>
                            </div>
                        </div>

                        <p>Warm regards,<br><strong>Team Pro Corporate League</strong></p>

                    </td>
                </tr>

                <!-- FOOTER -->
                 <tr>
                    <td align="center" style="background:#eef3fb;padding:15px;">
                        <p>India's Largest Corporate Cricket Ecosystem</p>
                        <p><a href="https://www.procorporateleague.com" style="color:#123a8c;text-decoration:none;">www.procorporateleague.com</a></p>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</body>
</html>
<?php
$emailBody = ob_get_clean();

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

    $mail->setFrom('sachin.gupta@procorporateleague.com', 'Pro Corporate League');
    $mail->addAddress($postData['email'], $person_name);
    $mail->addCC('sachin.gupta@procorporateleague.com', 'Sachin Gupta');
    $mail->addCC('sachin.gupta@corporateworldcup.com', 'Sachin Gupta');
    $mail->addCC('rifat.saleem@procorporateleague.com', 'Refat Saleem');
    
    $mail->CharSet  = 'UTF-8';
    $mail->Encoding = 'base64';
    $mail->isHTML(true);
    //$mail->Subject = !empty($postData['subject']) ? $postData['subject'] :  ucwords($postData['team_name']).' 🏆 Registration Confirmed | Your Road to the Corporate World Cup™ Begins';
    $mail->Subject = ucwords($postData['team_name']).' 🏆 Registration Confirmed | Your Road to the Corporate World Cup™ Begins';
    $mail->Body    = $emailBody;

    $mail->send();

    // Enterprise logging after successful send.
    // Controller resolves module/submodule/source dynamically using active_file_name/server path/URLs.
    $trackingResult = pcl_email_log_dynamic($mail, $emailBody ?? '', $postData ?? [], [
        'status' => 'sent',
        'delivery_status' => 'sent',
        'message' => 'Email sent successfully',
        'module_id' => 10,
        'submodule_id' => 10,
        'module_key' => 'lead_management',
        'submodule_key' => 'lead_management',
    ]);

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

    echo json_encode([
        "status_code" => 200,
        "status"      => "success",
        "message"     => "Registration email sent successfully",
        "tracking"    => $trackingResult
    ]);


    
} catch (Exception $e) {
    
    $trackingResult = pcl_email_log_dynamic($mail, $emailBody ?? '', $postData ?? [], [
        'status' => 'failed',
        'delivery_status' => 'failed',
        'message' => $mail->ErrorInfo ?? $e->getMessage(),
        'error_message' => $mail->ErrorInfo ?? $e->getMessage()
    ]);
echo json_encode([
        "status_code" => 500,
        "status"      => "error",
        "message"     => $mail->ErrorInfo
    ]);
}
