<?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.
================================ */
$__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(),
            ];
        }
    }
}



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

if (!is_array($requestData)) $requestData = [];

$leadRequestId = $requestData['lead_id'] ?? '';
$lEADID = $leadRequestId ?: '';

/* ===============================
   CURL CALL FROM LEAD ID
================================ */

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://procorporateleague.com/pcl_rest/api/v9/user/'.$lEADID,
  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',
));

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

$getData = json_decode($response, true);

//echo "<pre>"; print_r($getData);die;

$leadIdData = '';
if(!empty($getData) && !empty($getData['results']) && $getData['code'] === 200)
{
    $leadIdData = $getData['results'][0];
}


/* ===============================
   CURL CALL FROM MOBILE DATA
================================ */

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://procorporateleague.com/pcl_rest/api/v9/profile/mobile/'.$leadIdData['phone'],
  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',
));

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

$profileData = '';
$getData = json_decode($response, true);

if (!empty($getData) && !empty($getData['results']) && $getData['code'] === 200)
{
    $profileData = $getData['results'][0];
}


/* ===============================
   BUILD POST DATA
================================ */

$postData = [
    "subject"           => "{$leadIdData['full_name']}, Your AI-Powered PCL Profile is Live - Upload Video Now",
    "email"             => $profileData['email']                            ?? $leadIdData['email'] ?? '',
    "name"              => $leadIdData['full_name']                         ?? 'PCL',
    "city"              => $leadIdData['city']                              ?? '',
    "reference_id"      => $leadIdData['lead_id']                           ?? '',
    "registration_type" => $leadIdData['user_profile']                      ?? '',
    "mobile"            => $leadIdData['phone']                             ?? '',
    "user_id"           => $leadIdData['master_id']                         ?? '',
    "company_name"      => $profileData['company_name_individual']          ?? '',
    "person_name"       => $leadIdData['full_name']                         ?? '',
    "person_age"        => $profileData['age']                              ?? '',
];

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

$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']);
$corporate         = htmlspecialchars($postData['company_name']);
$age               = htmlspecialchars($postData['person_age']);
$cta_link          = "https://www.procorporateleague.com/2026/pcl/eleven11.php?lead_id=" . urlencode($postData['reference_id']) . "&id=" . urlencode($postData['user_id']);

if (!empty($registration_type) && $registration_type == 'teams') {
    $team         = 'team';
    $company_name = $postData['company_name'];
    $person_name  = $postData['person_name'];
} else {
    $team         = 'individual';
    $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']         ?? '',
];

/* ===============================
   DB CALLS
================================ */

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

// Email Template
$emailSql = "SELECT * FROM `email_template` WHERE id = 1";
$emailExe = mysqli_query($conn, $emailSql);
$emailRow = mysqli_fetch_assoc($emailExe);
if (empty($emailRow)) {
    echo json_encode([
        "status_code" => 400,
        "status"      => "ERROR",
        "message"     => "EMAIL TEMPLATE MISSING"
    ]);
    die;
}

/* ===============================
   BUILD CONDITIONAL BLOCKS
================================ */

// Age block
$age_block = !empty($age)
    ? "<p><strong>Age :</strong> " . ucwords($age) . "</p>"
    : '';

// CTA button (individual only)
$cta_button_block = ($registration_type === 'individual')
    ? "
        <table align='center' style='margin:18px auto;'>
            <tr>
                <td style='background:#0b1f4d;border-radius:6px;'>
                    <a href='{$cta_link}' style='display:inline-block;padding:12px 25px;color:#fff;text-decoration:none;font-weight:bold;'>
                        Upload your Video
                    </a>
                </td>
            </tr>
        </table>"
    : '';

// Next steps block
$next_steps_block = ($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 &amp; national broadcast opportunities</p>"
    : "
        <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 &amp; national broadcast opportunities</p>";

/* ===============================
   REPLACE PLACEHOLDERS IN TEMPLATE
================================ */

$emailBody = $emailRow['template_file'] ?? '';

$replacements = [
    '{{user_name}}'             => ucwords($user_name),
    '{{person_name}}'           => ucwords($person_name),
    '{{user_email}}'            => $user_email,
    '{{city}}'                  => ucwords($city),
    '{{reference_id}}'          => $reference_id,
    '{{registration_type}}'     => $registration_type,
    '{{user_mobile}}'           => $user_mobile,
    '{{corporate}}'             => ucwords($corporate),
    '{{team}}'                  => ucwords($team),
    '{{company_name}}'          => ucwords($company_name),
    '{{cta_link}}'              => $cta_link,
    '{{filePath}}'              => $filePath,
    '{{imgVersion}}'            => $imgVersion,
    '{{age_block}}'             => $age_block,
    '{{cta_button_block}}'      => $cta_button_block,
    '{{next_steps_block}}'      => $next_steps_block,
    '{{total_matches_played}}'  => number_format($statsArrayData['total_matches_played']  ?: 0),
    '{{total_runs_Scored}}'     => number_format($statsArrayData['total_runs_Scored']      ?: 0),
    '{{total_wickets_Claimed}}' => number_format($statsArrayData['total_wickets_Claimed']  ?: 0),
    '{{total_hundreds}}'        => number_format($statsArrayData['total_hundreds']         ?: 0),
    '{{total_fifties}}'         => number_format($statsArrayData['total_fifties']          ?: 0),
];

$emailBody = strtr($emailBody, $replacements);

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

    $mail->setFrom('sachin.gupta@procorporateleague.com', 'Pro Corporate League');
    $mail->addAddress($postData['email'], $postData['name']);
    //$mail->addAddress('zehraruhi82@gmail.com', 'Ruhi');
    //$mail->addCC('mohammad.mozammil@procorporateleague.com', 'Mozammil');
    //$mail->addCC('zehraruhi82@gmail.com', 'Ruhi');
    //$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'] : '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
    ]);
}