<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
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.
================================ */
$__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(),
            ];
        }
    }
}


/* ===============================GET JSON DATA================================ */
$data = json_decode(file_get_contents("php://input"), true);

$postData = [
    "subject"           => $data['subject']            ?? '',
    "email"             => $data['email']              ?? '',
    "name"              => $data['full_name']          ?? 'PCL',
    "city"              => $data['city']               ?? '',
    "reference_id"      => $data['lead_id']            ?? '',
    "registration_type" => $data['userType']           ?? '',
    "phone"             => $data['phone']              ?? '',
    "address"           => $data['address']            ?? '',
    "master_id"         => $data['master_id']          ?? '',
    'video_upload'      => $data['video_upload']       ?? ''
];



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['phone']);
$address           = htmlspecialchars($postData['address']);
$master_id         = htmlspecialchars($postData['master_id']);
$video_upload      = htmlspecialchars($postData['video_upload']);




/* ===============================EMAIL TEMPLATE================================ */
$pclLogo = 'https://www.procorporateleague.com/2026/pcl/Imp_PCL_Logo_Black.png';
$trophyImage = 'https://wplspeedqueen.com/email_api/cwctrophy.png';
$dashboardUrl = 'https://www.procorporateleague.com/2026/pcl/userDashboard.php?mobile=' . urlencode($user_mobile) . '&id=' . urlencode($reference_id);
$submittedDate = date('d M Y');
$displayLeadId = trim((string)$reference_id) !== '' ? $reference_id : 'PCL';
$dynamicSubject = trim((string)$user_name) . ' | Lead #' . $displayLeadId . ', Your PCL Video Submission Is Under Review';

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

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($dynamicSubject, ENT_QUOTES, 'UTF-8'); ?></title>
</head>

<body style="margin:0;padding:0;background:#eaf0fb;font-family:Arial,Helvetica,sans-serif;color:#071a3d;">
  <div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;">
    Your PCL video submission has been received and is now under AI evaluation.
  </div>

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

        <table role="presentation" width="760" cellpadding="0" cellspacing="0" border="0" style="width:760px;max-width:100%;background:#ffffff;border-radius:18px;overflow:hidden;box-shadow:0 22px 60px rgba(5,24,65,0.18);">

          <!-- Subject strip like Team Invitation template -->
          <tr>
            <td style="background:#061533;color:#ffffff;padding:13px 22px;border-bottom:1px solid rgba(239,179,33,0.55);">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                <tr>
                  <td style="font-size:12px;line-height:18px;font-weight:700;color:#ffffff;">
                    <span style="color:#ffffff;">Subject:</span>
                    <span style="color:#efb321;"><?php echo htmlspecialchars($user_name, ENT_QUOTES, 'UTF-8'); ?> | Lead #<?php echo htmlspecialchars($displayLeadId, ENT_QUOTES, 'UTF-8'); ?></span>
                    <span style="color:#ffffff;">, Your PCL Video Submission Is Under Review</span>
                  </td>
                  <td align="right" style="font-size:12px;line-height:18px;">
                    <a href="<?php echo htmlspecialchars($dashboardUrl, ENT_QUOTES, 'UTF-8'); ?>" style="color:#ffffff;text-decoration:underline;font-weight:700;">View dashboard</a>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- Hero -->
          <tr>
            <td style="background:#071a3d;">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                <tr>
                  <td width="58%" valign="top" style="padding:30px 28px 28px;background:linear-gradient(135deg,#061533 0%,#08265d 58%,#0b3b9a 100%);">
                    <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:22px;">
                      <tr>
                        <td style="background:#ffffff;border-radius:14px;padding:10px 15px;">
                          <img src="<?php echo htmlspecialchars($pclLogo, ENT_QUOTES, 'UTF-8'); ?>" width="190" alt="Pro Corporate League" style="display:block;border:0;max-width:190px;height:auto;">
                        </td>
                      </tr>
                    </table>

                    <div style="display:inline-block;background:#16813b;color:#ffffff;border-radius:9px;padding:8px 13px;font-size:12px;line-height:16px;font-weight:900;letter-spacing:.4px;text-transform:uppercase;margin-bottom:18px;">
                      &#10003; Video Submission Confirmed
                    </div>

                    <h1 style="margin:0 0 14px;font-family:Georgia,'Times New Roman',serif;font-size:36px;line-height:42px;color:#ffffff;font-weight:900;letter-spacing:-0.8px;">
                      Your PCL Video Submission Is <span style="color:#efb321;">Under Review</span>
                    </h1>

                    <p style="margin:0 0 14px;font-size:19px;line-height:25px;color:#efb321;font-weight:900;">
                      Hi <?php echo htmlspecialchars($user_name, ENT_QUOTES, 'UTF-8'); ?>,
                    </p>

                    <p style="margin:0;font-size:15px;line-height:24px;color:#e9f0ff;">
                      Thank you for submitting your cricket video to Pro Corporate League.
                      Our AI evaluation system is now reviewing your performance.
                    </p>

                    <p style="margin:12px 0 0;font-size:14px;line-height:23px;color:#cdd9f4;">
                      You will receive updates on your dashboard and registered email.
                    </p>
                  </td>

                  <td width="42%" valign="middle" align="center" style="padding:26px 20px;background:#061533;">
                    <img src="<?php echo htmlspecialchars($trophyImage, ENT_QUOTES, 'UTF-8'); ?>" width="245" alt="Corporate World Cup Trophy" style="display:block;border:0;width:245px;max-width:100%;height:auto;margin:0 auto 18px;">
                    <div style="border:1px solid #efb321;border-radius:14px;padding:14px 12px;color:#ffffff;font-size:15px;line-height:21px;font-weight:900;letter-spacing:.3px;">
                      Corporate World Cup&trade;<br>
                      <span style="color:#efb321;">Player Pathway</span>
                    </div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- Submission Details -->
          <tr>
            <td style="background:#ffffff;padding:28px 26px 12px;">
              <h2 style="margin:0;text-align:center;font-size:20px;line-height:26px;color:#071a3d;font-weight:900;letter-spacing:.4px;text-transform:uppercase;">
                Your Submission Details
              </h2>
              <div style="width:54px;height:3px;background:#efb321;margin:10px auto 22px;border-radius:999px;"></div>

              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border:1px solid #dce5f4;border-radius:16px;overflow:hidden;">
                <tr>
                  <td width="25%" align="center" style="padding:20px 12px;border-right:1px solid #e7edf7;">
                    <div style="width:48px;height:48px;border-radius:50%;background:#071a3d;color:#efb321;margin:0 auto 10px;font-size:22px;line-height:48px;font-weight:900;">P</div>
                    <div style="font-size:11px;line-height:15px;color:#6b7a99;font-weight:900;text-transform:uppercase;">Player Name</div>
                    <div style="margin-top:6px;font-size:15px;line-height:20px;color:#071a3d;font-weight:900;"><?php echo htmlspecialchars($user_name, ENT_QUOTES, 'UTF-8'); ?></div>
                  </td>
                  <td width="25%" align="center" style="padding:20px 12px;border-right:1px solid #e7edf7;">
                    <div style="width:48px;height:48px;border-radius:50%;background:#071a3d;color:#efb321;margin:0 auto 10px;font-size:18px;line-height:48px;font-weight:900;">ID</div>
                    <div style="font-size:11px;line-height:15px;color:#6b7a99;font-weight:900;text-transform:uppercase;">Lead ID</div>
                    <div style="margin-top:6px;font-size:17px;line-height:20px;color:#103a9c;font-weight:900;"><?php echo htmlspecialchars($displayLeadId, ENT_QUOTES, 'UTF-8'); ?></div>
                  </td>
                  <td width="25%" align="center" style="padding:20px 12px;border-right:1px solid #e7edf7;">
                    <div style="width:48px;height:48px;border-radius:50%;background:#071a3d;color:#efb321;margin:0 auto 10px;font-size:20px;line-height:48px;font-weight:900;">D</div>
                    <div style="font-size:11px;line-height:15px;color:#6b7a99;font-weight:900;text-transform:uppercase;">Submission Date</div>
                    <div style="margin-top:6px;font-size:15px;line-height:20px;color:#071a3d;font-weight:900;"><?php echo htmlspecialchars($submittedDate, ENT_QUOTES, 'UTF-8'); ?></div>
                  </td>
                  <td width="25%" align="center" style="padding:20px 12px;">
                    <div style="width:48px;height:48px;border-radius:50%;background:#071a3d;color:#efb321;margin:0 auto 10px;font-size:20px;line-height:48px;font-weight:900;">AI</div>
                    <div style="font-size:11px;line-height:15px;color:#6b7a99;font-weight:900;text-transform:uppercase;">Submitted For</div>
                    <div style="margin-top:6px;font-size:15px;line-height:20px;color:#071a3d;font-weight:900;">Player Evaluation</div>
                  </td>
                </tr>
              </table>

              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:14px;border:1px solid #dce5f4;border-radius:14px;overflow:hidden;">
                <tr>
                  <td style="padding:13px 16px;background:#f6f8fd;width:34%;font-size:12px;color:#6b7a99;font-weight:900;text-transform:uppercase;">City</td>
                  <td style="padding:13px 16px;background:#ffffff;font-size:14px;color:#071a3d;font-weight:800;"><?php echo htmlspecialchars($city, ENT_QUOTES, 'UTF-8'); ?></td>
                </tr>
                <tr>
                  <td style="padding:13px 16px;background:#f6f8fd;border-top:1px solid #e7edf7;font-size:12px;color:#6b7a99;font-weight:900;text-transform:uppercase;">Category</td>
                  <td style="padding:13px 16px;background:#ffffff;border-top:1px solid #e7edf7;font-size:14px;color:#071a3d;font-weight:800;"><?php echo htmlspecialchars($registration_type, ENT_QUOTES, 'UTF-8'); ?></td>
                </tr>
                <tr>
                  <td style="padding:13px 16px;background:#f6f8fd;border-top:1px solid #e7edf7;font-size:12px;color:#6b7a99;font-weight:900;text-transform:uppercase;">Registered Email</td>
                  <td style="padding:13px 16px;background:#ffffff;border-top:1px solid #e7edf7;font-size:14px;color:#103a9c;font-weight:800;word-break:break-all;"><?php echo htmlspecialchars($user_email, ENT_QUOTES, 'UTF-8'); ?></td>
                </tr>
                <?php if (!empty($video_upload)) : ?>
                <tr>
                  <td style="padding:13px 16px;background:#f6f8fd;border-top:1px solid #e7edf7;font-size:12px;color:#6b7a99;font-weight:900;text-transform:uppercase;">Video</td>
                  <td style="padding:13px 16px;background:#ffffff;border-top:1px solid #e7edf7;font-size:14px;color:#103a9c;font-weight:800;word-break:break-all;">
                    <a href="<?php echo htmlspecialchars($video_upload, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" style="color:#103a9c;text-decoration:underline;">View submitted video</a>
                  </td>
                </tr>
                <?php endif; ?>
              </table>
            </td>
          </tr>

          <!-- What Happens Next -->
          <tr>
            <td style="background:#ffffff;padding:18px 26px 10px;">
              <h2 style="margin:0;text-align:center;font-size:20px;line-height:26px;color:#071a3d;font-weight:900;text-transform:uppercase;">
                What Happens Next?
              </h2>
              <div style="width:54px;height:3px;background:#efb321;margin:10px auto 22px;border-radius:999px;"></div>

              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                <tr>
                  <td width="20%" valign="top" align="center" style="padding:0 6px;">
                    <div style="width:54px;height:54px;border-radius:50%;background:#071a3d;border:2px solid #efb321;color:#efb321;line-height:54px;font-size:20px;font-weight:900;margin:0 auto 10px;">1</div>
                    <div style="font-size:12px;line-height:16px;color:#071a3d;font-weight:900;">Video Received</div>
                    <div style="font-size:11px;line-height:16px;color:#6b7a99;margin-top:5px;">Your submission has been received.</div>
                  </td>
                  <td width="20%" valign="top" align="center" style="padding:0 6px;">
                    <div style="width:54px;height:54px;border-radius:50%;background:#071a3d;border:2px solid #efb321;color:#efb321;line-height:54px;font-size:20px;font-weight:900;margin:0 auto 10px;">2</div>
                    <div style="font-size:12px;line-height:16px;color:#071a3d;font-weight:900;">AI Evaluation</div>
                    <div style="font-size:11px;line-height:16px;color:#6b7a99;margin-top:5px;">Performance is being analysed.</div>
                  </td>
                  <td width="20%" valign="top" align="center" style="padding:0 6px;">
                    <div style="width:54px;height:54px;border-radius:50%;background:#071a3d;border:2px solid #efb321;color:#efb321;line-height:54px;font-size:20px;font-weight:900;margin:0 auto 10px;">3</div>
                    <div style="font-size:12px;line-height:16px;color:#071a3d;font-weight:900;">Expert Validation</div>
                    <div style="font-size:11px;line-height:16px;color:#6b7a99;margin-top:5px;">PCL team validates AI insights.</div>
                  </td>
                  <td width="20%" valign="top" align="center" style="padding:0 6px;">
                    <div style="width:54px;height:54px;border-radius:50%;background:#071a3d;border:2px solid #efb321;color:#efb321;line-height:54px;font-size:20px;font-weight:900;margin:0 auto 10px;">4</div>
                    <div style="font-size:12px;line-height:16px;color:#071a3d;font-weight:900;">Shortlist Update</div>
                    <div style="font-size:11px;line-height:16px;color:#6b7a99;margin-top:5px;">Selected players are notified.</div>
                  </td>
                  <td width="20%" valign="top" align="center" style="padding:0 6px;">
                    <div style="width:54px;height:54px;border-radius:50%;background:#071a3d;border:2px solid #efb321;color:#efb321;line-height:54px;font-size:20px;font-weight:900;margin:0 auto 10px;">5</div>
                    <div style="font-size:12px;line-height:16px;color:#071a3d;font-weight:900;">Challenger Round</div>
                    <div style="font-size:11px;line-height:16px;color:#6b7a99;margin-top:5px;">Shortlisted players move ahead.</div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- CTA -->
          <tr>
            <td style="background:#ffffff;padding:28px 26px;">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#071a3d;border-radius:16px;overflow:hidden;">
                <tr>
                  <td width="55%" valign="middle" style="padding:24px 24px;color:#ffffff;">
                    <div style="font-size:20px;line-height:26px;font-weight:900;color:#efb321;text-transform:uppercase;">One Step Closer To Glory</div>
                    <div style="font-size:14px;line-height:22px;color:#e9f0ff;margin-top:8px;">
                      Keep performing. Keep believing. The Corporate World Cup&trade; pathway is waiting for you.
                    </div>
                  </td>
                  <td width="45%" valign="middle" align="center" style="padding:24px 22px;border-left:1px solid rgba(255,255,255,0.18);">
                    <a href="<?php echo htmlspecialchars($dashboardUrl, ENT_QUOTES, 'UTF-8'); ?>" style="display:inline-block;background:#efb321;color:#071a3d;text-decoration:none;font-size:15px;line-height:20px;font-weight:900;padding:15px 28px;border-radius:10px;text-transform:uppercase;">
                      View My Dashboard
                    </a>
                    <div style="font-size:12px;line-height:18px;color:#cdd9f4;margin-top:10px;">Track evaluation, updates and next steps</div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="background:#061533;padding:26px 28px;color:#ffffff;">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                <tr>
                  <td valign="middle" width="42%">
                    <div style="background:#ffffff;border-radius:12px;padding:9px 13px;display:inline-block;">
                      <img src="<?php echo htmlspecialchars($pclLogo, ENT_QUOTES, 'UTF-8'); ?>" width="155" alt="Pro Corporate League" style="display:block;border:0;max-width:155px;height:auto;">
                    </div>
                  </td>
                  <td valign="middle" width="28%" align="center" style="font-size:12px;line-height:19px;color:#cdd9f4;">
                    <strong style="color:#efb321;">Pro Corporate League</strong><br>
                    Where corporate talent becomes legends
                  </td>
                  <td valign="middle" width="30%" align="right" style="font-size:12px;line-height:20px;color:#cdd9f4;">
                    <strong style="color:#efb321;">Need Help?</strong><br>
                    support@procorporateleague.com<br>
                    +91 93540 82788
                  </td>
                </tr>
              </table>
              <div style="height:1px;background:rgba(255,255,255,0.15);margin:22px 0 14px;"></div>
              <div style="text-align:center;font-size:11px;line-height:18px;color:#8fa3c8;">
                This email was sent because your video was submitted on the PCL player portal.<br>
                &copy; <?php echo date('Y'); ?> Pro Corporate League. All rights reserved.
              </div>
            </td>
          </tr>

        </table>

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

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

    $mail->setFrom('sachin.gupta@procorporateleague.com', 'Pro Corporate League');
    $mail->addAddress($user_email, $user_name);
    $mail->addCC('sachin.gupta@procorporateleague.com', 'Sachin Gupta');
    $mail->addCC('rifat.saleem@procorporateleague.com', 'Refat Saleem');

    //$mail->addCC('hussainmstr@gmail.com', 'Admin');

    $mail->CharSet  = 'UTF-8';
    $mail->Encoding = 'base64';
    $mail->isHTML(true);
    $mail->Subject = !empty($postData['subject']) ? $postData['subject'] : 'Registration Confirmed – Pro Corporate League';
    $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'
    ]);

    echo json_encode([
        "status_code" => 200,
        "status"      => "success",
        "message"     => "Video submission 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
    ]);
}