<?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.
================================ */
$__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_local_tracking_debug_log')) {
    function pcl_email_local_tracking_debug_log(array $record)
    {
        $logDir = __DIR__ . '/email_tracking_logs';
        if (!is_dir($logDir)) {
            @mkdir($logDir, 0775, true);
        }

        $line = json_encode($record, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
        @file_put_contents($logDir . '/email_tracking_debug_' . date('Ymd') . '.log', $line, FILE_APPEND | LOCK_EX);
    }
}

if (!function_exists('pcl_email_track_legacy_fallback')) {
    function pcl_email_track_legacy_fallback(array $payload, $reason = '')
    {
        $trackingUrls = [
            'https://www.procorporateleague.com/pcl_rest/api/v15/email/track/legacy-call',
            'https://www.procorporateleague.com/pcl_rest/api/v15/email/tracking/legacy-log',
        ];

        $payload['tracking_fallback_reason'] = $reason;
        $payload['tracking_attempted_at'] = date('c');
        $payload['source_domain'] = $_SERVER['HTTP_HOST'] ?? 'wplspeedqueen.com';

        $attempts = [];

        if (!function_exists('curl_init')) {
            $attempts[] = [
                'tracking_status' => 'failed',
                'reason' => 'curl_init not available'
            ];
            pcl_email_local_tracking_debug_log([
                'status' => 'failed_before_curl',
                'reason' => $reason,
                'payload' => $payload,
                'attempts' => $attempts,
            ]);
            return [
                'tracking_status' => 'failed',
                'reason' => 'curl_init not available',
                'attempts' => $attempts,
            ];
        }

        foreach ($trackingUrls as $url) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
                CURLOPT_CONNECTTIMEOUT => 8,
                CURLOPT_TIMEOUT => 15,
                CURLOPT_FOLLOWLOCATION => true,
            ]);

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

            $decoded = json_decode((string)$response, true);
            $attempt = [
                'url' => $url,
                'http_code' => $httpCode,
                'curl_error' => $curlError,
                'response' => $decoded ?: $response,
            ];
            $attempts[] = $attempt;

            if ($curlError === '' && $httpCode >= 200 && $httpCode < 300) {
                pcl_email_local_tracking_debug_log([
                    'status' => 'success',
                    'reason' => $reason,
                    'payload_summary' => [
                        'active_file_name' => $payload['active_file_name'] ?? null,
                        'lead_id' => $payload['lead_id'] ?? null,
                        'recipient_email' => $payload['recipient_email'] ?? null,
                        'delivery_status' => $payload['delivery_status'] ?? null,
                    ],
                    'attempt' => $attempt,
                ]);
                return [
                    'tracking_status' => 'success',
                    'mode' => 'fallback_direct_post',
                    'url' => $url,
                    'http_code' => $httpCode,
                    'response' => $decoded ?: $response,
                    'attempts' => $attempts,
                ];
            }
        }

        pcl_email_local_tracking_debug_log([
            'status' => 'failed_after_all_attempts',
            'reason' => $reason,
            'payload' => $payload,
            'attempts' => $attempts,
        ]);

        return [
            'tracking_status' => 'failed',
            'mode' => 'fallback_direct_post',
            'reason' => $reason,
            'attempts' => $attempts,
        ];
    }
}

if (!function_exists('pcl_email_log_dynamic')) {
    function pcl_email_log_dynamic($mail, $emailBody, array $postData = [], array $extra = [])
    {
        $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 {
            if (class_exists('EmailTrackingApiClient')) {
                $clientResult = EmailTrackingApiClient::trackLegacy($payload);

                // If the client exists but the API did not accept/save the log, retry with direct fallback URLs.
                $clientStatus = is_array($clientResult) ? strtolower((string)($clientResult['tracking_status'] ?? $clientResult['status'] ?? '')) : '';
                if (in_array($clientStatus, ['failed', 'error', 'skipped'], true)) {
                    $fallbackResult = pcl_email_track_legacy_fallback($payload, 'EmailTrackingApiClient returned ' . $clientStatus);
                    return [
                        'tracking_status' => $fallbackResult['tracking_status'] ?? 'unknown',
                        'client_result' => $clientResult,
                        'fallback_result' => $fallbackResult,
                    ];
                }

                return $clientResult;
            }

            return pcl_email_track_legacy_fallback($payload, 'EmailTrackingApiClient not found');
        } catch (Throwable $trackingException) {
            $fallbackResult = pcl_email_track_legacy_fallback($payload, 'EmailTrackingApiClient exception: ' . $trackingException->getMessage());
            return [
                'tracking_status' => $fallbackResult['tracking_status'] ?? 'failed',
                'error' => $trackingException->getMessage(),
                'fallback_result' => $fallbackResult,
            ];
        }
    }
}


/* ===============================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================================ */
ob_start();

?>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>PCL – Registration Confirmed</title>
</head>
<body style="margin:0;padding:0;background:#eef2fb;">

<table width="100%" cellpadding="0" cellspacing="0" border="0"
       style="background:#eef2fb;" class="wrap">
<tr><td align="center" style="padding:28px 12px;" class="wrap">

  <!-- ═══ CARD ═══ -->
  <table width="600" cellpadding="0" cellspacing="0" border="0"
         style="max-width:600px;width:100%;border-radius:22px;overflow:hidden;
                box-shadow:0 24px 64px rgba(16,58,156,.16);" class="card">

    <!-- HEADER -->
    <tr>
      <td style="background:linear-gradient(160deg,#0a2060 0%,#103a9c 55%,#1647bf 100%);
                  padding:36px 32px 30px;text-align:center;" class="hpad">

        <!-- Logo -->
        <table cellpadding="0" cellspacing="0" style="margin:0 auto 20px;">
          <tr>
            <td style="background:rgba(255,255,255,.13);border:1px solid rgba(255,255,255,.2);
                        border-radius:14px;padding:9px 20px;">
              <span style="font-size:20px;vertical-align:middle;">🏏</span>
              <span style="font-family:Georgia,serif;font-size:14px;font-weight:700;color:#fff;
                           letter-spacing:.6px;margin-left:8px;vertical-align:middle;">
                Pro Corporate League
              </span>
            </td>
          </tr>
        </table>

        <!-- Badge -->
        <table cellpadding="0" cellspacing="0" style="margin:0 auto 16px;">
          <tr>
            <td style="background:#efb321;border-radius:999px;padding:7px 22px;">
              <span style="font-family:Arial,sans-serif;font-size:11px;font-weight:700;
                           color:#16213a;letter-spacing:.9px;text-transform:uppercase;">
                ✅ &nbsp;Registration Confirmed
              </span>
            </td>
          </tr>
        </table>

        <!-- Headline -->
        <h1 class="hl" style="margin:0 0 10px;font-size:30px;font-weight:900;color:#fff;
                    line-height:1.12;letter-spacing:-1px;font-family:Georgia,serif;">
          Welcome to PCL,<br>
          <span style="color:#efb321;"><?php echo htmlspecialchars($user_name); ?> 🎯</span>
        </h1>
        <p style="margin:0;font-size:14px;color:rgba(255,255,255,.88);
                   line-height:1.65;font-family:Arial,sans-serif;">
          Your profile is now part of India's largest<br>
          <strong style="color:#efb321;">corporate cricket ecosystem.</strong>
        </p>

        <!-- Accent dots -->
        <table cellpadding="0" cellspacing="0" style="margin:20px auto 0;">
          <tr>
            <td style="width:7px;height:7px;background:rgba(255,255,255,.22);border-radius:50%;"></td>
            <td style="width:6px;"></td>
            <td style="width:50px;height:7px;background:#efb321;border-radius:999px;"></td>
            <td style="width:6px;"></td>
            <td style="width:7px;height:7px;background:rgba(255,255,255,.22);border-radius:50%;"></td>
          </tr>
        </table>
      </td>
    </tr>

    <!-- GREETING -->
    <tr>
      <td style="background:#fff;padding:28px 32px 0;" class="bpad0">
        <p style="margin:0 0 6px;font-size:18px;font-weight:700;color:#103a9c;
                   font-family:Georgia,serif;">
          Hi <?php echo htmlspecialchars($user_name); ?>,
        </p>
        <p style="margin:0;font-size:14px;color:#4a5568;line-height:1.72;
                   font-family:Arial,sans-serif;">
          Thank you for registering with the
          <strong style="color:#103a9c;">Pro Corporate League</strong>.
          Your profile has been successfully received and is now active
          in our player evaluation system.
        </p>
      </td>
    </tr>

    <!-- REGISTRATION DETAILS -->
    <tr>
      <td style="background:#fff;padding:22px 32px 0;" class="bpad0">
        <p style="margin:0 0 12px;font-size:15px;font-weight:800;color:#103a9c;
                   font-family:Georgia,serif;">
          📋 &nbsp;Registration Details
        </p>
        <table width="100%" cellpadding="0" cellspacing="0"
               style="border:1.5px solid #e2e8f4;border-radius:16px;overflow:hidden;">

          <!-- PCL ID -->
          <tr>
            <td class="dlabel" style="padding:13px 16px;background:#eef3ff;
                border-bottom:1px solid #e2e8f4;width:38%;font-family:Arial,sans-serif;
                font-size:12px;font-weight:700;color:#6b7a99;text-transform:uppercase;
                letter-spacing:.5px;">PCL ID</td>
            <td class="dval" style="padding:13px 16px;background:#eef3ff;
                border-bottom:1px solid #e2e8f4;font-family:Arial,sans-serif;">
              <strong style="font-size:17px;color:#103a9c;font-weight:900;letter-spacing:1.5px;">
                <?php echo htmlspecialchars($reference_id); ?>
              </strong>
            </td>
          </tr>
          <!-- Name -->
          <tr>
            <td class="dlabel" style="padding:12px 16px;background:#fafbff;
                border-bottom:1px solid #e2e8f4;font-family:Arial,sans-serif;font-size:12px;
                font-weight:700;color:#6b7a99;text-transform:uppercase;letter-spacing:.5px;">Name</td>
            <td class="dval" style="padding:12px 16px;background:#fafbff;
                border-bottom:1px solid #e2e8f4;font-size:14px;color:#16213a;font-weight:600;
                font-family:Arial,sans-serif;">
              <?php echo htmlspecialchars($user_name); ?>
            </td>
          </tr>
          <!-- City -->
          <tr>
            <td class="dlabel" style="padding:12px 16px;background:#fff;
                border-bottom:1px solid #e2e8f4;font-family:Arial,sans-serif;font-size:12px;
                font-weight:700;color:#6b7a99;text-transform:uppercase;letter-spacing:.5px;">City</td>
            <td class="dval" style="padding:12px 16px;background:#fff;
                border-bottom:1px solid #e2e8f4;font-size:14px;color:#16213a;font-weight:600;
                font-family:Arial,sans-serif;">
              <?php echo htmlspecialchars($city); ?>
            </td>
          </tr>
          <!-- Category -->
          <tr>
            <td class="dlabel" style="padding:12px 16px;background:#fafbff;
                border-bottom:1px solid #e2e8f4;font-family:Arial,sans-serif;font-size:12px;
                font-weight:700;color:#6b7a99;text-transform:uppercase;letter-spacing:.5px;">Category</td>
            <td class="dval" style="padding:12px 16px;background:#fafbff;
                border-bottom:1px solid #e2e8f4;font-size:14px;color:#16213a;font-weight:600;
                font-family:Arial,sans-serif;">
              <?php echo htmlspecialchars($registration_type); ?>
            </td>
          </tr>
          <!-- Email -->
          <tr>
            <td class="dlabel" style="padding:12px 16px;background:#fff;
                border-bottom:1px solid #e2e8f4;font-family:Arial,sans-serif;font-size:12px;
                font-weight:700;color:#6b7a99;text-transform:uppercase;letter-spacing:.5px;">Email</td>
            <td class="dval" style="padding:12px 16px;background:#fff;
                border-bottom:1px solid #e2e8f4;font-size:14px;color:#103a9c;font-weight:600;
                font-family:Arial,sans-serif;word-break:break-all;">
              <?php echo htmlspecialchars($user_email); ?>
            </td>
          </tr>
          <!-- Phone -->
          <tr>
            <td class="dlabel" style="padding:12px 16px;background:#fafbff;
                font-family:Arial,sans-serif;font-size:12px;font-weight:700;color:#6b7a99;
                text-transform:uppercase;letter-spacing:.5px;">Phone</td>
            <td class="dval" style="padding:12px 16px;background:#fafbff;
                font-size:14px;color:#16213a;font-weight:600;font-family:Arial,sans-serif;">
              <?php echo htmlspecialchars($user_mobile); ?>
            </td>
          </tr>
          <!-- video -->
          <tr>
            <td class="dlabel" style="padding:12px 16px;background:#fff;
                border-bottom:1px solid #e2e8f4;font-family:Arial,sans-serif;font-size:12px;
                font-weight:700;color:#6b7a99;text-transform:uppercase;letter-spacing:.5px;">Video</td>
            <td class="dval" style="padding:12px 16px;background:#fff;
                border-bottom:1px solid #e2e8f4;font-size:14px;color:#103a9c;font-weight:600;
                font-family:Arial,sans-serif;word-break:break-all;">
               <a href="<?php echo htmlspecialchars($video_upload); ?>" target="_blank">
                <?php echo htmlspecialchars($video_upload); ?>
              </a>
            </td>
          </tr>

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


    <!-- WHAT HAPPENS NEXT -->
    <tr>
      <td style="background:#fff;padding:22px 32px 0;" class="bpad0">
        <p style="margin:0 0 12px;font-size:15px;font-weight:800;color:#103a9c;
                   font-family:Georgia,serif;">
          ⚡ &nbsp;What Happens Next?
        </p>
        <table width="100%" cellpadding="0" cellspacing="0"
               style="border:1.5px solid #e2e8f4;border-radius:16px;overflow:hidden;">

          <tr>
            <td style="padding:14px 16px;background:#fffdf4;border-bottom:1px solid #eaeffa;">
              <table cellpadding="0" cellspacing="0"><tr>
                <td style="padding-right:12px;font-size:20px;" valign="top">🤖</td>
                <td valign="top">
                  <strong style="font-size:13px;color:#16213a;display:block;margin-bottom:3px;
                                  font-family:Arial,sans-serif;">AI Engine Analysing Your Performance</strong>
                  <span style="font-size:12px;color:#6b7a99;font-family:Arial,sans-serif;">
                    ⏳ Turnaround: <strong style="color:#a07010;">Within 24 hours</strong>
                  </span>
                </td>
              </tr></table>
            </td>
          </tr>

          <tr>
            <td style="padding:14px 16px;background:#fafbff;border-bottom:1px solid #eaeffa;">
              <table cellpadding="0" cellspacing="0"><tr>
                <td style="padding-right:12px;font-size:20px;" valign="top">👤</td>
                <td valign="top">
                  <strong style="font-size:13px;color:#16213a;display:block;margin-bottom:3px;
                                  font-family:Arial,sans-serif;">Profile Reviewed by PCL Team</strong>
                  <span style="font-size:12px;color:#6b7a99;font-family:Arial,sans-serif;">
                    Our evaluation team reviews AI-shortlisted profiles.
                  </span>
                </td>
              </tr></table>
            </td>
          </tr>

          <tr>
            <td style="padding:14px 16px;background:#f7faff;border-bottom:1px solid #eaeffa;">
              <table cellpadding="0" cellspacing="0"><tr>
                <td style="padding-right:12px;font-size:20px;" valign="top">📣</td>
                <td valign="top">
                  <strong style="font-size:13px;color:#16213a;display:block;margin-bottom:3px;
                                  font-family:Arial,sans-serif;">Shortlisted Players Notified</strong>
                  <span style="font-size:12px;color:#6b7a99;font-family:Arial,sans-serif;">
                    Merit-based shortlisting for the Challenger Round.
                  </span>
                </td>
              </tr></table>
            </td>
          </tr>

          <tr>
            <td style="padding:14px 16px;background:#fff;">
              <table cellpadding="0" cellspacing="0"><tr>
                <td style="padding-right:12px;font-size:20px;" valign="top">📲</td>
                <td valign="top">
                  <strong style="font-size:13px;color:#16213a;display:block;margin-bottom:3px;
                                  font-family:Arial,sans-serif;">Updates via Email &amp; WhatsApp</strong>
                  <span style="font-size:12px;color:#6b7a99;font-family:Arial,sans-serif;">
                    Keep your phone &amp; WhatsApp active for further updates.
                  </span>
                </td>
              </tr></table>
            </td>
          </tr>

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


    <!-- CTA -->
    <tr>
      <td style="background:#fff;padding:26px 32px;" class="bpad">
        <table width="100%" cellpadding="0" cellspacing="0">
          <tr>
            <td align="center">
              <a href="https://www.procorporateleague.com/2026/pcl/userDashboard.php?mobile=<?php echo urlencode($user_mobile); ?>&id=<?php echo urlencode($reference_id); ?>"
                 class="cta-btn"
                 style="display:inline-block;
                         background:linear-gradient(180deg,#1242b8,#0d2f7d);
                         color:#fff;font-size:15px;font-weight:800;text-decoration:none;
                         padding:16px 48px;border-radius:14px;letter-spacing:.4px;
                         box-shadow:0 12px 28px rgba(16,58,156,.28);
                         font-family:Arial,sans-serif;">
                🏠 &nbsp;Open Your Dashboard
              </a>
              
              <p style="margin:10px 0 0;font-size:12px;color:#8a9ab8;
                          font-family:Arial,sans-serif;">
                Track your evaluation status, match updates &amp; progression
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>

    <!-- FOOTER -->
    <tr>
      <td style="background:#0b2466;padding:24px 32px;text-align:center;" class="fpad">
        <p style="margin:0 0 4px;font-size:14px;font-weight:700;color:#efb321;
                   font-family:Georgia,serif;">Team Pro Corporate League</p>
        <a href="https://www.procorporateleague.com"
           style="font-size:13px;color:rgba(255,255,255,.65);text-decoration:none;
                   display:block;margin-bottom:14px;font-family:Arial,sans-serif;">
          🌐 www.procorporateleague.com
        </a>
        <table cellpadding="0" cellspacing="0" style="margin:0 auto 14px;">
          <tr>
            <td style="padding:7px 18px;background:rgba(239,179,33,.15);
                        border:1px solid rgba(239,179,33,.3);border-radius:999px;">
              <span style="font-size:12px;color:#efb321;font-weight:700;
                           font-family:Arial,sans-serif;letter-spacing:.5px;">
                #CorporateKaWorldCup
              </span>
            </td>
          </tr>
        </table>
        <p style="margin:0 0 4px;font-size:12px;color:rgba(255,255,255,.4);
                   font-family:Arial,sans-serif;line-height:1.6;">
          This email was sent because you registered on the PCL player portal.<br>
          If you did not register, please ignore this email.
        </p>
        <p style="margin:10px 0 0;font-size:11px;color:rgba(255,255,255,.25);
                   font-family:Arial,sans-serif;">
          © 2025 Pro Corporate League. All rights reserved.
        </p>
      </td>
    </tr>

  </table>
  <!-- /CARD -->

</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"     => "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 ?: $e->getMessage(),
        "tracking"    => $trackingResult
    ]);
}