<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header("Content-Type: application/json");
/**
 * send_invoice_email.php
 *
 * PCL Invoice Email Sender
 * ─────────────────────────
 * - Invoice ka same design HTML email body mein embed hota hai
 * - Wahi PDF attachment ke saath attach hoti hai (DomPDF se generate)
 *
 * REQUIREMENTS:
 *   composer require phpmailer/phpmailer
 *   composer require dompdf/dompdf
 */

require '../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
use Dompdf\Dompdf;
use Dompdf\Options;

// ════════════════════════════════════════════════════════════
//  SMTP CONFIGURATION
// ════════════════════════════════════════════════════════════
define('SMTP_HOST',     'smtp.gmail.com');
define('SMTP_PORT',     587);
define('SMTP_USER',     'sachin.gupta@procorporateleague.com');
//define('SMTP_PASS',     'hpctcjjbvwvvvvzn');
define('SMTP_PASS',     'mwhqomapdbzzvjeb');

define('SMTP_FROM',     'sachin.gupta@procorporateleague.com');
define('SMTP_FROM_NAME','Pro Cricket League');

define('PCL_LOGO_URL', 'https://procorporateleague.com/Imp_PCL_Logo_Black.png');

// ════════════════════════════════════════════════════════════
//  MAIN FUNCTION
// ════════════════════════════════════════════════════════════
function sendInvoiceEmail(array $data): array
{
    date_default_timezone_set("Asia/Kolkata");

    $leadId         = $data['lead_id']        ?? '';
    $name           = $data['name']           ?? 'Player';
    $email          = $data['email']          ?? '';
    $mobile         = $data['mobile']         ?? '';
    $tournament     = $data['tournament']     ?? 'PCL Eleven 11 - Challenger Round';
    $category       = $data['category']       ?? '';
    $base           = (float)($data['base']           ?? 0);
    $discount       = (float)($data['discount']       ?? 0);
    $gst            = (float)($data['gst']            ?? 0);
    $paymentPending = (bool)($data['payment_pending'] ?? true);
    $transactionId  = $data['transaction_id'] ?? '';

    $subtotal  = max(0, $base - $discount);
    $total     = $subtotal + $gst;
    $cgst      = $gst / 2;
    $sgst      = $gst / 2;

    $invoiceNo = "PCL-INV-" . ($leadId !== '' ? $leadId : date("YmdHis"));
    $date      = date("d M Y");
    $dateTime  = date("d M Y, h:i A");

    $companyName    = "PRO CRICKET LEAGUE PVT LTD";
    $companyGSTIN   = "09AAJCP4097L1ZO";
    $companyState   = "H15,BSI Business Park Sector 63 Noida, India";
    $companyEmail   = "pcl@procorporateleague.com";
    $companyWebsite = "www.procorporateleague.com";
    $sacCode        = "998599";

    $statusLabel = $paymentPending ? "UNPAID" : "PAID";

    if (empty($email)) {
        return ['success' => false, 'message' => 'Recipient email missing'];
    }

    $pdfString = generateInvoicePdf(compact(
        'leadId','name','email','mobile','tournament','category',
        'base','discount','gst','subtotal','total','cgst','sgst',
        'paymentPending','transactionId','statusLabel',
        'invoiceNo','date','dateTime',
        'companyName','companyGSTIN','companyState','companyEmail','companyWebsite','sacCode'
    ));

    $emailHtml = buildEmailHtml(compact(
        'name','invoiceNo','date','statusLabel','paymentPending',
        'tournament','category','leadId','mobile','email',
        'base','discount','subtotal','cgst','sgst','gst','total',
        'transactionId','sacCode',
        'companyName','companyGSTIN','companyEmail'
    ));

    $mail = new PHPMailer(true);

/*
|--------------------------------------------------------------------------
| PCL Enterprise Email Logging Helper
|--------------------------------------------------------------------------
| Dynamic logging only. No hardcoded module/submodule/project/page mapping here.
| Controller resolves mapping using active_file_name, script_name, URLs and file path.
*/
if (!function_exists('pcl_enterprise_email_current_url')) {
    function pcl_enterprise_email_current_url() {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
        $host   = $_SERVER['HTTP_HOST'] ?? '';
        $uri    = $_SERVER['REQUEST_URI'] ?? '';
        return $host ? ($scheme . $host . $uri) : '';
    }
}

if (!function_exists('pcl_enterprise_email_find_value')) {
    function pcl_enterprise_email_find_value(array $ctx, array $keys, $default = '') {
        foreach ($keys as $key) {
            if (isset($ctx[$key]) && $ctx[$key] !== '' && $ctx[$key] !== null) {
                return $ctx[$key];
            }
        }
        return $default;
    }
}

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

if (!function_exists('pcl_enterprise_email_safe_json')) {
    function pcl_enterprise_email_safe_json($value) {
        return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}

if (!function_exists('pcl_enterprise_email_collect_attachments')) {
    function pcl_enterprise_email_collect_attachments($mail, array $ctx = array()) {
        $items = array();

        if (isset($ctx['attachmentUrls']) && is_array($ctx['attachmentUrls'])) {
            foreach ($ctx['attachmentUrls'] as $url) {
                if (!empty($url)) {
                    $items[] = array('type' => 'url', 'url' => $url, 'name' => basename(parse_url($url, PHP_URL_PATH) ?: $url));
                }
            }
        }

        if (isset($ctx['attachment_urls']) && is_array($ctx['attachment_urls'])) {
            foreach ($ctx['attachment_urls'] as $url) {
                if (!empty($url)) {
                    $items[] = array('type' => 'url', 'url' => $url, 'name' => basename(parse_url($url, PHP_URL_PATH) ?: $url));
                }
            }
        }

        if (isset($ctx['attachmentUrl']) && !empty($ctx['attachmentUrl'])) {
            $items[] = array('type' => 'url', 'url' => $ctx['attachmentUrl'], 'name' => basename(parse_url($ctx['attachmentUrl'], PHP_URL_PATH) ?: $ctx['attachmentUrl']));
        }

        if (is_object($mail) && method_exists($mail, 'getAttachments')) {
            foreach ($mail->getAttachments() as $att) {
                $path = $att[0] ?? '';
                $name = $att[2] ?? basename($path);
                $items[] = array(
                    'type' => 'phpmailer_attachment',
                    'name' => $name,
                    'path' => $path,
                    'url'  => (preg_match('/^https?:\/\//i', $path) ? $path : '')
                );
            }
        }

        return $items;
    }
}

if (!function_exists('pcl_enterprise_email_first_to')) {
    function pcl_enterprise_email_first_to($mail) {
        if (is_object($mail) && method_exists($mail, 'getToAddresses')) {
            $to = $mail->getToAddresses();
            if (!empty($to[0])) {
                return array(
                    'email' => $to[0][0] ?? '',
                    'name'  => $to[0][1] ?? ''
                );
            }
        }
        return array('email' => '', 'name' => '');
    }
}

if (!function_exists('pcl_enterprise_email_log')) {
    function pcl_enterprise_email_log($mail, $deliveryStatus = 'sent', $errorMessage = '', array $ctx = array()) {
        $clientPath = __DIR__ . '/EmailTrackingApiClient.php';
        if (!class_exists('EmailTrackingApiClient') && file_exists($clientPath)) {
            require_once $clientPath;
        }

        if (!class_exists('EmailTrackingApiClient') || !method_exists('EmailTrackingApiClient', 'trackLegacy')) {
            return array('tracking_status' => 'skipped', 'reason' => 'EmailTrackingApiClient not available');
        }

        $firstTo = pcl_enterprise_email_first_to($mail);
        $html = '';
        $subject = '';
        $messageId = '';

        if (is_object($mail)) {
            $html = property_exists($mail, 'Body') ? (string)$mail->Body : '';
            $subject = property_exists($mail, 'Subject') ? (string)$mail->Subject : '';
            $messageId = property_exists($mail, 'lastMessageID') ? (string)$mail->lastMessageID : '';
        }

        $attachments = pcl_enterprise_email_collect_attachments($mail, $ctx);
        $attachmentUrls = array();
        foreach ($attachments as $att) {
            if (!empty($att['url'])) {
                $attachmentUrls[] = $att['url'];
            }
        }

        $leadId = pcl_enterprise_email_find_value($ctx, array('lead_id','leadId','leadID','leadid','id'), null);
        $teamId = pcl_enterprise_email_find_value($ctx, array('team_id','teamId','teamID'), null);
        $playerId = pcl_enterprise_email_find_value($ctx, array('player_id','playerId','user_id','userId'), null);
        $mobile = pcl_enterprise_email_find_value($ctx, array('mobile','phone','recipient_mobile','contact'), '');
        $recipientEmail = pcl_enterprise_email_find_value($ctx, array('recipient_email','email','user_email','team_email'), $firstTo['email']);
        $recipientName = pcl_enterprise_email_find_value($ctx, array('recipient_name','name','teamName','team_name','user_name'), $firstTo['name']);

        $payload = array(
            'active_file_name'      => basename(__FILE__),
            'script_name'           => basename(__FILE__),
            'server_full_path'      => __FILE__,
            'server_file_path'      => __FILE__,

            'current_email_url'     => pcl_enterprise_email_current_url(),
            'direct_email_url'      => pcl_enterprise_email_current_url(),
            'calling_file_url'      => ($_SERVER['HTTP_REFERER'] ?? ''),
            'calling_page_url'      => ($_SERVER['HTTP_REFERER'] ?? ''),
            'public_calling_url'    => ($_SERVER['HTTP_REFERER'] ?? pcl_enterprise_email_current_url()),
            'request_uri'           => ($_SERVER['REQUEST_URI'] ?? ''),

            'lead_id'               => $leadId,
            'team_id'               => $teamId,
            'player_id'             => $playerId,
            'recipient_name'        => $recipientName,
            'recipient_email'       => $recipientEmail,
            'recipient_mobile'      => $mobile,

            'subject'               => pcl_enterprise_email_find_value($ctx, array('subject','emailSubject'), $subject),
            'preheader'             => pcl_enterprise_email_find_value($ctx, array('preheader','emailPreheader'), ''),

            'full_email_html'       => $html,
            'full_email_text'       => pcl_enterprise_email_flatten_text($html),

            'attachment_urls'       => implode(',', $attachmentUrls),
            'attachments_json'      => pcl_enterprise_email_safe_json($attachments),
            'attachment_count'      => count($attachments),

            'delivery_status'       => $deliveryStatus,
            'status'                => $deliveryStatus,
            'error_message'         => $errorMessage,
            'provider_message_id'   => $messageId,

            'payload_json'          => pcl_enterprise_email_safe_json(array(
                'file' => basename(__FILE__),
                'request' => $_REQUEST,
                'context_keys' => array_keys($ctx)
            )),
            'response_json'         => pcl_enterprise_email_safe_json(array(
                'delivery_status' => $deliveryStatus,
                'error_message' => $errorMessage,
                'provider_message_id' => $messageId
            ))
        );

        // FIX: previously this caught Throwable/Exception and called
        // pcl_enterprise_email_log() again from inside its own catch block,
        // which could recurse forever if the tracking API kept failing.
        // Now we just log locally and return — no recursion.
        try {
            return EmailTrackingApiClient::trackLegacy($payload);
        } catch (\Throwable $t) {
            error_log('pcl_enterprise_email_log: tracking failed - ' . $t->getMessage());
            return array('tracking_status' => 'failed', 'error' => $t->getMessage());
        }
    }
}

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_enterprise_track')) {
    function pcl_email_enterprise_track($mail = null, $status = 'sent', array $extra = array()) {
        try {
            $to = array();
            if (is_object($mail) && method_exists($mail, 'getToAddresses')) {
                $to = $mail->getToAddresses();
            }
            $firstTo = isset($to[0]) ? $to[0] : array('', '');
            $recipientEmail = $extra['recipient_email'] ?? ($firstTo[0] ?? '');
            $recipientName  = $extra['recipient_name']  ?? ($firstTo[1] ?? '');

            $subject = is_object($mail) && isset($mail->Subject) ? $mail->Subject : ($extra['subject'] ?? '');
            $body    = is_object($mail) && isset($mail->Body) ? $mail->Body : ($extra['full_email_html'] ?? '');

            $payload = array_merge(array(
                'recipient_email'   => $recipientEmail,
                'recipient_name'    => $recipientName,
                'subject'           => $subject,
                'full_email_html'   => $body,
                'status'            => $status,
                'delivery_status'   => $status,
                'error_message'     => $extra['error_message'] ?? null,
                'active_file_name'  => basename(__FILE__),
                'request_uri'       => $_SERVER['REQUEST_URI'] ?? '',
            ), $extra);

            if (class_exists('EmailTrackingApiClient') && method_exists('EmailTrackingApiClient', 'trackLegacy')) {
                return EmailTrackingApiClient::trackLegacy($payload);
            }

            return array('tracking_status' => 'skipped', 'reason' => 'EmailTrackingApiClient class not found');
        } catch (Throwable $e) {
            return array('tracking_status' => 'failed', 'error' => $e->getMessage());
        }
    }
}


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'] ?? '';
        // FIX: was falling back to `$leadId` referencing itself (undefined
        // local variable) — now falls back to $GLOBALS['leadId'] or ''.
        $leadId = $extra['lead_id'] ?? $postData['lead_id'] ?? $postData['reference_id'] ?? ($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 = [
            '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'] ?? '',

            'full_email_html'    => $html,
            // FIX: pcl_email_flatten_text() did not exist anywhere in this
            // file — the only defined flattener is pcl_enterprise_email_flatten_text().
            'full_email_text'    => pcl_enterprise_email_flatten_text($html),

            'attachment_urls'    => implode(',', $attachmentUrls),
            'attachments_json'   => json_encode($attachmentUrls, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'attachment_count'   => count($attachmentUrls),

            // FIX: pcl_email_runtime_url() / pcl_email_public_file_url() did
            // not exist anywhere in this file. Both calls caused a fatal
            // "Call to undefined function" error right after every
            // successful $mail->send() — meaning the email actually went
            // out, but the script crashed before it could return the
            // {"success":true} JSON response. Replaced with the helper
            // that is actually defined, pcl_enterprise_email_current_url().
            'current_email_url'  => pcl_enterprise_email_current_url(),
            'public_calling_url' => pcl_enterprise_email_current_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_enterprise_email_current_url(),
            'server_full_path'   => __FILE__,
            'server_file_path'   => __FILE__,
            'script_name'        => basename(__FILE__),
            'active_file_name'   => basename(__FILE__),
            'request_uri'        => $_SERVER['REQUEST_URI'] ?? null,

            'status'             => $status,
            'delivery_status'    => $deliveryStatus,
            'provider_message_id'=> $messageId,
            'error_message'      => $extra['error_message'] ?? null,

            '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(),
            ];
        }
    }
}

function pcl_track_email_if_available($mail, $extra = []) {
    try {
        if (function_exists('pcl_email_enterprise_track_send')) {
            return pcl_email_enterprise_track_send($mail, $extra);
        }
        if (class_exists('EmailTrackingApiClient') && method_exists('EmailTrackingApiClient', 'trackLegacy')) {
            $payload = array_merge([
                'active_file_name' => basename(__FILE__),
                'lead_id' => $extra['lead_id'] ?? null,
                'recipient_email' => $extra['recipient_email'] ?? '',
                'recipient_name' => $extra['recipient_name'] ?? '',
                'subject' => $mail->Subject ?? '',
                'status' => 'sent',
                'source' => 'proceed_to_payment'
            ], $extra);
            return EmailTrackingApiClient::trackLegacy($payload);
        }
    } catch (Throwable $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
    return ['success' => false, 'message' => 'Tracking client not available'];
}



try {
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER;
        $mail->Password   = SMTP_PASS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = SMTP_PORT;
        $mail->CharSet    = 'UTF-8';
        $mail->Encoding   = 'base64';

        $mail->setFrom(SMTP_FROM, SMTP_FROM_NAME);
        $mail->addAddress($email, $name);
        $mail->addCC('pcl@procorporateleague.com', 'PCL');
        $mail->addCC('rifat.saleem@procorporateleague.com', 'Rifat Saleem');
        $mail->addCC('sachin.gupta@procorporateleague.com', 'Sachin Gupta');
        $mail->addCC('sachin.gupta@corporateworldcup.com', 'Sachin Gupta');
        //$mail->addCC('mohammad.mozammil@procorporateleague.com', 'Mozammil');

        // $subject = $paymentPending
        //     ? "Payment Pending — Invoice {$invoiceNo} | PCL Eleven 11 - Challenger Round"
        //     : "Payment Confirmed — Invoice {$invoiceNo} | PCL Eleven 11 - Challenger Round";


        $subject = $paymentPending
            ? "Pending Payment Reminder | PCL Eleven 11 Challenger Round"
            : "PCL Payment Confirmed | Challenger Round Registration Successful";
        
        $mail->Subject = $subject;

        $mail->isHTML(true);
        $mail->Body    = $emailHtml;
        $mail->AltBody = "Dear {$name},\n\nPlease find your PCL Tax Invoice {$invoiceNo} attached.\n\nTotal Payable: Rs. " . number_format($total, 2) . "\nStatus: {$statusLabel}\n\nRegards,\nPro Cricket League";

        $pdfFilename = "PCL_Invoice_{$invoiceNo}.pdf";
        $mail->addStringAttachment($pdfString, $pdfFilename, PHPMailer::ENCODING_BASE64, 'application/pdf');

        $mail->send();
        pcl_enterprise_email_log($mail, 'sent', '', get_defined_vars());

        // FIX: was passing undefined variables $emailBody and $postData
        // (never set anywhere in this function), so the tracking record
        // silently stored an empty body and an empty payload. Now passes
        // the real $emailHtml body and $data input array, plus the
        // recipient fields so the tracker doesn't have to guess them.
        $trackingResult = pcl_email_log_dynamic($mail, $emailHtml, $data, [
            'status' => 'sent',
            'delivery_status' => 'sent',
            'message' => 'Email sent successfully',
            'lead_id' => $leadId,
            'recipient_email' => $email,
            'recipient_name' => $name,
            'recipient_mobile' => $mobile,
            'subject' => $subject,
            'module_id' => 4,
            'submodule_id' => 4,
            'module_key' => 'payment_reminder',
            'submodule_key' => 'payment_reminder',
        ]);


        
        $tracking = pcl_track_email_if_available($mail, [
            'lead_id' => $leadId,
            'mobile' => $mobile,
            'recipient_email' => $email,
            'recipient_name' => $name,
            'subject' => $subject,
            'module_id' => 4,
            'submodule_id' => 4,
            'module_key' => 'payment_reminder',
            'submodule_key' => 'payment_reminder',
            'active_file_name' => basename(__FILE__),
            'calling_file_url' => $_SERVER['HTTP_REFERER'] ?? '',
            'full_email_html' => $emailHtml
        ]);

        return ['success' => true, 'message' => "Invoice email sent to {$email}"];

    } catch (Exception $e) {
        // FIX: $mail->ErrorInfo is now guarded with isset($mail) so this
        // catch block itself can't throw a secondary fatal error.
        pcl_enterprise_email_log(isset($mail) ? $mail : null, 'failed', (isset($mail) && is_object($mail) && property_exists($mail, 'ErrorInfo')) ? $mail->ErrorInfo : $e->getMessage(), get_defined_vars());
        return ['success' => false, 'message' => "Mailer Error: " . (isset($mail) ? $mail->ErrorInfo : $e->getMessage())];
    }
}

// ════════════════════════════════════════════════════════════
//  PDF GENERATION (DomPDF)
// ════════════════════════════════════════════════════════════
function generateInvoicePdf(array $d): string
{
    $paymentPending = $d['paymentPending'];
    $statusLabel    = $d['statusLabel'];

    $statusBg    = $paymentPending ? '#fee2e2' : '#dcfce7';
    $statusColor = $paymentPending ? '#991b1b' : '#14532d';
    $statusBorder= $paymentPending ? '#fecaca' : '#bbf7d0';
    $noteBg      = $paymentPending ? '#fff7ed' : '#ecfdf3';
    $noteBorder  = $paymentPending ? '#fed7aa' : '#bbf7d0';
    $noteColor   = $paymentPending ? '#7c2d12' : '#14532d';
    $noteIcon    = $paymentPending ? '&#9888; Payment Pending' : '&#10003; Payment Received';
    $noteText    = $paymentPending
        ? 'This invoice is currently unpaid. Please complete payment to confirm your participation.'
        : 'Thank you. Your payment has been recorded successfully.' . (!empty($d['transactionId']) ? '<br>Transaction ID: ' . htmlspecialchars($d['transactionId']) : '');

    $baseF     = number_format($d['base'], 2);
    $discountF = number_format($d['discount'], 2);
    $subtotalF = number_format($d['subtotal'], 2);
    $cgstF     = number_format($d['cgst'], 2);
    $sgstF     = number_format($d['sgst'], 2);
    $gstF      = number_format($d['gst'], 2);
    $totalF    = number_format($d['total'], 2);
    $logoUrl   = PCL_LOGO_URL;

    $html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
    @page {
        margin: 12mm 10mm 38mm 10mm;   /* Increased bottom margin for footer */
        size: A4;
    }
    * { 
        box-sizing: border-box; 
        margin: 0; 
        padding: 0; 
    }
    body { 
        font-family: DejaVu Sans, Arial, sans-serif; 
        font-size: 12px; 
        color: #0f172a; 
        background: #fff; 
        position: relative;
        line-height: 1.4;
    }

    /* ==================== UNPAID WATERMARK (Smaller Size) ==================== */
    .watermark {
        position: absolute;
        top: 48%;
        left: 40%;
        transform: translate(-50%, -50%) rotate(-35deg);
        font-size: 55px;           /* Smaller size */
        font-weight: 900;
        color: #ef4444;
        opacity: 0.14;
        pointer-events: none;
        z-index: 10;
        text-transform: uppercase;
        letter-spacing: 9px;
        white-space: nowrap;
        border: 6px solid #ef4444;
        padding: 14px 55px;
        border-radius: 12px;
        user-select: none;
    }

    .inv-header { 
        background: #123a8c; 
        color: #fff; 
        padding: 22px 24px; 
        position: relative; 
        z-index: 20; 
    }
    .company-name { 
        font-size: 16px; 
        font-weight: 700; 
        text-transform: uppercase; 
        letter-spacing: .05em; 
        margin-bottom: 6px; 
    }
    .company-details { 
        font-size: 10px; 
        line-height: 1.45; 
        color: rgba(255,255,255,.78); 
    }
    .inv-title { 
        font-size: 25px; 
        font-weight: 900; 
        color: #fff; 
        text-align: right; 
        margin-bottom: 8px; 
    }
    .status-pill { 
        display: inline-block; 
        padding: 4px 12px; 
        border-radius: 99px; 
        font-size: 9.5px; 
        font-weight: 900; 
        letter-spacing: .08em; 
        text-transform: uppercase; 
        background: {$statusBg}; 
        color: {$statusColor}; 
        border: 1px solid {$statusBorder}; 
    }
    .inv-meta { 
        font-size: 10px; 
        line-height: 1.5; 
        color: rgba(255,255,255,.82); 
        text-align: right; 
        margin-top: 6px; 
    }

    .info-card { 
        background: #f8fafc; 
        border: 1px solid #e2e8f0; 
        border-radius: 8px; 
        padding: 13px; 
        vertical-align: top; 
        width: 50%; 
    }
    .info-title { 
        font-size: 9px; 
        font-weight: 900; 
        text-transform: uppercase; 
        letter-spacing: .08em; 
        color: #103a9c; 
        margin-bottom: 7px; 
    }
    .info-text { 
        font-size: 11px; 
        line-height: 1.45; 
        color: #334155; 
        font-weight: 600; 
    }

    .section-title { 
        font-size: 11px; 
        font-weight: 900; 
        text-transform: uppercase; 
        letter-spacing: .06em; 
        color: #111827; 
        margin: 16px 0 9px; 
    }

    .line-table { 
        width: 100%; 
        border-collapse: collapse; 
        border: 1px solid #e2e8f0; 
    }
    .line-table th { 
        background: #f1f5f9; 
        color: #334155; 
        font-size: 9px; 
        font-weight: 900; 
        text-transform: uppercase; 
        letter-spacing: .04em; 
        padding: 10px 11px; 
        text-align: left; 
        border-bottom: 1px solid #e2e8f0; 
    }
    .line-table td { 
        padding: 11px 11px; 
        border-bottom: 1px solid #edf2f7; 
        font-size: 11px; 
        color: #334155; 
        line-height: 1.4; 
    }
    .right { text-align: right; }
    .amount { font-weight: 800; color: #0f172a; }
    .desc-sub { 
        font-size: 9.5px; 
        color: #64748b; 
        margin-top: 4px; 
        line-height: 1.3;
    }

    .summary-table { 
        width: 48%; 
        margin-left: auto; 
        border-collapse: collapse; 
        border: 1px solid #e2e8f0; 
    }
    .summary-table td { 
        padding: 9px 12px; 
        border-bottom: 1px solid #edf2f7; 
        font-size: 11px; 
        color: #334155; 
        line-height: 1.45;
    }
    .summary-table .grand-total td { 
        background: #123a8c; 
        color: #fff; 
        font-size: 13.5px; 
        font-weight: 900; 
    }

    .payment-note { 
        margin-top: 15px; 
        padding: 12px 14px; 
        border: 1px solid {$noteBorder}; 
        background: {$noteBg}; 
        color: {$noteColor}; 
        border-radius: 8px; 
        font-size: 11px; 
        line-height: 1.5; 
    }
    .terms { 
        margin-top: 15px; 
        padding: 12px 14px; 
        background: #f8fafc; 
        border: 1px solid #e2e8f0; 
        border-radius: 8px; 
        font-size: 10px; 
        line-height: 1.55; 
        color: #64748b; 
    }

    /* ==================== FIXED FOOTER ==================== */
    .inv-footer-wrap { 
        margin-top: 40px; 
        padding-top: 20px; 
        border-top: 2px solid #e2e8f0; 
    }
    .footer-logo {
        width: 58px;
        height: auto;
        margin-bottom: 8px;
        filter: brightness(0.9);
    }
    .inv-footer td { 
        vertical-align: bottom; 
        font-size: 10px; 
        line-height: 1.65; 
        color: #64748b; 
    }
    .sign-line { 
        border-top: 1px solid #cbd5e1; 
        width: 190px; 
        margin-bottom: 6px; 
        margin-left: auto; 
    }
    .sign-text { 
        text-align: right; 
        font-size: 10px; 
        color: #334155; 
    }
</style>
</head>
<body>

    <!-- UNPAID WATERMARK -->
    <div class="watermark">UNPAID</div>

    <div class="inv-header">
        <table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td width="60%" style="vertical-align:middle;">
                    <div class="company-name">{$d['companyName']}</div>
                    <div class="company-details">
                        GSTIN: {$d['companyGSTIN']}<br>
                        {$d['companyState']}<br>
                        {$d['companyEmail']} | {$d['companyWebsite']}
                    </div>
                </td>
                <td width="40%" style="vertical-align:top;">
                    <div class="inv-title">TAX INVOICE</div>
                    <div style="text-align:right;margin-bottom:6px;">
                        <span class="status-pill">{$statusLabel}</span>
                    </div>
                    <div class="inv-meta">
                        <strong>Invoice No:</strong> {$d['invoiceNo']}<br>
                        <strong>Date:</strong> {$d['date']}<br>
                        <strong>Generated:</strong> {$d['dateTime']}
                    </div>
                </td>
            </tr>
        </table>
    </div>

    <div style="padding:0 4px; position: relative; z-index: 5;">
        <table width="100%" cellpadding="0" cellspacing="8" style="margin:16px 0;border-collapse:separate;border-spacing:8px;">
            <tr>
                <td class="info-card">
                    <div class="info-title">Bill To</div>
                    <div class="info-text">
                        <strong>{$d['name']}</strong><br>
                        Email: {$d['email']}<br>
                        Mobile: {$d['mobile']}
                    </div>
                </td>
                <td class="info-card">
                    <div class="info-title">Registration Details</div>
                    <div class="info-text">
                        Lead ID: {$d['leadId']}<br>
                        Category: {$d['category']}<br>
                        Tournament: {$d['tournament']}<br>
                        Payment: <strong>{$statusLabel}</strong>
                    </div>
                </td>
            </tr>
        </table>

        <div class="section-title">Invoice Line Items</div>
        <table class="line-table">
            <thead>
                <tr>
                    <th style="width:46%;">Description</th>
                    <th>HSN/SAC</th>
                    <th class="right">Base Amount</th>
                    <th class="right">Discount</th>
                    <th class="right">Taxable Value</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><strong>PCL Challenger Round</strong><div class="desc-sub">7 matches fees for PCL Eleven 11 Challenger Round</div></td>
                    <td>{$d['sacCode']}</td>
                    <td class="right amount">&#8377;{$baseF}</td>
                    <td class="right amount">&#8377;{$discountF}</td>
                    <td class="right amount">&#8377;{$subtotalF}</td>
                </tr>
            </tbody>
        </table>

        <div style="margin-top:14px;">
            <table class="summary-table">
                <tr><td>Subtotal / Taxable</td><td class="right amount">&#8377;{$subtotalF}</td></tr>
                <tr><td>CGST (9%)</td><td class="right amount">&#8377;{$cgstF}</td></tr>
                <tr><td>SGST (9%)</td><td class="right amount">&#8377;{$sgstF}</td></tr>
                <tr><td>Total GST (18%)</td><td class="right amount">&#8377;{$gstF}</td></tr>
                <tr class="grand-total">
                    <td>Total Payable</td>
                    <td class="right">&#8377;{$totalF}</td>
                </tr>
            </table>
        </div>

        <div class="payment-note"><strong>{$noteIcon}:</strong> {$noteText}</div>
        <div class="terms">
            <strong>Terms &amp; Notes:</strong><br>
            1. This is a system-generated tax invoice and does not require a physical signature.<br>
            2. Participation is subject to PCL rules, eligibility, verification, and event terms.<br>
            3. Fees once paid shall be governed by the refund/cancellation policy applicable to the event.
        </div>

        <!-- ==================== FIXED FOOTER ==================== -->
        <div class="inv-footer-wrap" style="margin-left:15px; margin-right:15px;">
            <table width="100%" cellpadding="0" cellspacing="0" class="inv-footer">
                <tr>
                    <td style="width:55%;">
                        <!-- <img src="{$logoUrl}" alt="PCL Logo" class="footer-logo" /><br> -->
                        <strong>{$d['companyName']}</strong><br>
                        GSTIN: {$d['companyGSTIN']}<br>
                        Support: {$d['companyEmail']}
                    </td>
                    <td style="text-align:right; vertical-align:bottom;">
                        <div class="sign-line"></div>
                        <div class="sign-text">
                            Authorized Signatory<br>
                            <strong>Pro Cricket League Pvt Ltd</strong>
                        </div>
                    </td>
                </tr>
            </table>
        </div>

    </div>
</body>
</html>
HTML;

    $options = new Options();
    $options->set('defaultFont', 'DejaVu Sans');
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isRemoteEnabled', true);

    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    return $dompdf->output();
}

// ════════════════════════════════════════════════════════════
//  EMAIL HTML BODY BUILDER
// ════════════════════════════════════════════════════════════
function buildEmailHtml(array $d): string
{
    $paymentPending = $d['paymentPending'];
    $statusLabel    = $d['statusLabel'];

    $statusBg    = $paymentPending ? '#fee2e2' : '#dcfce7';
    $statusColor = $paymentPending ? '#991b1b' : '#14532d';
    $statusBorder= $paymentPending ? '#fecaca' : '#bbf7d0';
    $noteBg      = $paymentPending ? '#fff7ed' : '#ecfdf3';
    $noteBorder  = $paymentPending ? '#fed7aa' : '#bbf7d0';
    $noteColor   = $paymentPending ? '#7c2d12' : '#14532d';
    $noteText    = $paymentPending
        ? '&#9888;&#65039; <strong>Payment is still pending.</strong> Please complete your payment at the earliest to confirm your participation in the tournament.'
        : '&#9989; <strong>Your payment has been received and confirmed.</strong> Please find the attached PDF invoice for your records.' . (!empty($d['transactionId']) ? ' Transaction ID: <strong>' . htmlspecialchars($d['transactionId']) . '</strong>' : '');

    $baseF     = number_format($d['base'], 2);
    $discountF = number_format($d['discount'], 2);
    $subtotalF = number_format($d['subtotal'], 2);
    $cgstF     = number_format($d['cgst'], 2);
    $sgstF     = number_format($d['sgst'], 2);
    $gstF      = number_format($d['gst'], 2);
    $totalF    = number_format($d['total'], 2);
    $name      = htmlspecialchars($d['name']);
    $invoiceNo = htmlspecialchars($d['invoiceNo']);
    $logoUrl   = PCL_LOGO_URL;
    $year      = date('Y');

    return <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>PCL Tax Invoice {$invoiceNo}</title>
</head>
<body style="margin:0;padding:0;background:#f0f4ff;font-family:Arial,sans-serif;">

<div style="max-width:640px;margin:30px auto;background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 12px 40px rgba(15,23,42,.12);">

  <!-- HEADER - Same color as PDF -->
  <div style="background:#123a8c;padding:28px 32px;">
    <table width="100%" cellpadding="0" cellspacing="0"><tr>
      <td style="vertical-align:middle;">
        <table cellpadding="0" cellspacing="0"><tr>
         
          <td style="vertical-align:top;">
            <div style="font-size:19px;font-weight:900;color:#fff;text-transform:uppercase;letter-spacing:.04em;margin-bottom:4px;">
              <img src="{$logoUrl}" alt="PCL Logo" style="width:180px;height:auto;display:block;filter:brightness(0) invert(1);" />
            </div>
           <div style="font-size:11px; color: #ffffff !important; line-height:1.45;">
              {$d['companyEmail']} | www.procorporateleague.com
          </div>
            
          </td>
        </tr></table>
      </td>
      <td style="text-align:right;vertical-align:top;">
        <div style="font-size:23px;font-weight:900;color:#fff;margin-bottom:8px;">TAX INVOICE</div>
        <div style="display:inline-block;background:{$statusBg};color:{$statusColor};border:1px solid {$statusBorder};padding:5px 14px;border-radius:99px;font-size:10px;font-weight:900;letter-spacing:.08em;">
          {$statusLabel}
        </div>
      </td>
    </tr></table>
  </div>

  <!-- BODY -->
  <div style="padding:28px 32px;">

    <p style="font-size:15px;color:#0f172a;margin-bottom:8px;">Dear <strong>{$name}</strong>,</p>
    <p style="font-size:13px;color:#475569;line-height:1.6;margin-bottom:22px;">
      Please find your PCL Tax Invoice details below. The PDF invoice is attached to this email for your records.
    </p>

    <!-- Status Note -->
    <div style="background:{$noteBg};border:1px solid {$noteBorder};color:{$noteColor};border-radius:10px;padding:14px 16px;font-size:13px;line-height:1.55;margin-bottom:22px;">
      {$noteText}
    </div>

    <!-- Invoice + Player Meta -->
    <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:20px;">
      <tr>
        <td width="50%" style="vertical-align:top;padding-right:8px;">
          <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:14px;">
            <div style="font-size:9px;font-weight:900;text-transform:uppercase;letter-spacing:.08em;color:#103a9c;margin-bottom:8px;">Invoice Details</div>
            <div style="font-size:12px;line-height:1.7;color:#334155;">
              <strong>Invoice No:</strong> {$invoiceNo}<br>
              <strong>Date:</strong> {$d['date']}<br>
              <strong>Lead ID:</strong> {$d['leadId']}
            </div>
          </div>
        </td>
        <td width="50%" style="vertical-align:top;padding-left:8px;">
          <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:14px;">
            <div style="font-size:9px;font-weight:900;text-transform:uppercase;letter-spacing:.08em;color:#103a9c;margin-bottom:8px;">Player Details</div>
            <div style="font-size:12px;line-height:1.7;color:#334155;">
              <strong>Mobile:</strong> {$d['mobile']}<br>
              <strong>Category:</strong> {$d['category']}<br>
              <strong>Tournament:</strong> PCL Eleven 11 - Challenger Round
            </div>
          </div>
        </td>
      </tr>
    </table>

    <!-- Amount Summary -->
    <table width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;margin-bottom:22px;">
      <tr style="background:#f1f5f9;">
        <th style="padding:10px 14px;text-align:left;font-size:10px;font-weight:900;text-transform:uppercase;color:#334155;border-bottom:1px solid #e2e8f0;">Description</th>
        <th style="padding:10px 14px;text-align:right;font-size:10px;font-weight:900;text-transform:uppercase;color:#334155;border-bottom:1px solid #e2e8f0;">Amount (&#8377;)</th>
      </tr>
      <tr>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;">Base Amount</td>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;text-align:right;font-weight:700;">&#8377;{$baseF}</td>
      </tr>
      <tr>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;">Discount</td>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;text-align:right;font-weight:700;">- &#8377;{$discountF}</td>
      </tr>
      <tr>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;">Taxable Value</td>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;text-align:right;font-weight:700;">&#8377;{$subtotalF}</td>
      </tr>
      <tr>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;">CGST (9%)</td>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;text-align:right;">&#8377;{$cgstF}</td>
      </tr>
      <tr>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;">SGST (9%)</td>
        <td style="padding:11px 14px;border-bottom:1px solid #f0f4f8;font-size:12px;color:#334155;text-align:right;">&#8377;{$sgstF}</td>
      </tr>
      <tr>
        <td style="padding:14px;background:#123a8c;font-size:15px;font-weight:900;color:#fff;">Total Payable</td>
        <td style="padding:14px;background:#123a8c;font-size:15px;font-weight:900;color:#efb321;text-align:right;">&#8377;{$totalF}</td>
      </tr>
    </table>

    <!-- Terms -->
    <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:14px;font-size:11px;line-height:1.7;color:#64748b;margin-bottom:20px;">
      <strong style="color:#334155;">Terms &amp; Notes:</strong><br>
      1. This is a system-generated tax invoice and does not require a physical signature.<br>
      2. Participation is subject to PCL rules, eligibility, verification, and event terms.<br>
      3. Fees once paid shall be governed by the refund/cancellation policy applicable to the event.
    </div>

    <p style="font-size:12px;color:#64748b;line-height:1.7;">
      For any queries, contact us at 
      <a href="mailto:{$d['companyEmail']}" style="color:#ffffff; font-weight:600; text-decoration:underline;">
        {$d['companyEmail']}
      </a><br>
      <strong style="color:#334155;">{$d['companyName']}</strong> | GSTIN: {$d['companyGSTIN']}
    </p>

  </div><!-- /body -->

  <!-- FOOTER -->
  <div style="background:#f1f5f9;padding:16px 32px;text-align:center;border-top:1px solid #e2e8f0;">
    <p style="margin:0;font-size:11px;color:#94a3b8;">
      &copy; {$year} Pro Cricket League Pvt Ltd &nbsp;|&nbsp; This is an auto-generated email, please do not reply.
    </p>
  </div>

</div><!-- /email wrap -->
</body>
</html>
HTML;
}

// ════════════════════════════════════════════════════════════
//  DIRECT BROWSER / CLI CALL
// ════════════════════════════════════════════════════════════
if (php_sapi_name() !== 'cli' && basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'] ?? '')) {

    $input = json_decode(file_get_contents('php://input'), true) ?? $_POST ?? [];
    //echo "<pre>"; print_r($input);die;


    // whatsapp payment pending
    include('whatsapp/constant.php');
    // Meta WhatsApp Cloud API configuration
    $accessToken   = ACCESS_TOKEN;
    $phoneNumberId = PHONE_NUMBER_ID;

    // Replace this with the exact approved template name shown in Meta.
    $templateName = PAYMENT_PENDING;

    // Example usage values
    // $recipientMobile = '9818596699'; // WhatsApp recipient
    // $playerName        = 'Sachin';   // {{1}} body - naam
    // $referenceId        = '123456';  // registration/reference id (agar payment link ke liye chahiye)
    // $registeredMobile   = '9818596699';

    $recipientMobile    = $input['mobile']??''; // WhatsApp recipient
    $playerName         = $input['name']??'';   // {{1}} body - naam
    $registrationId     = $input['lead_id']??'';    // {{2}} body - registration id
    $registeredMobile   = $input['mobile']??'';

    // Keep digits only and include country code.
    $whatsappNumber = preg_replace('/\D+/', '', $recipientMobile);
    if (strlen($whatsappNumber) === 10) {
        $whatsappNumber = '91' . $whatsappNumber;
    }

    // Payment link (body me text ke roop me dikhega)
    $paymentUrl = 'https://www.procorporateleague.com/2026/pcl/playerInvoice.php'
        . '?id=' . urlencode($registrationId)
        . '&mobile=' . urlencode($registeredMobile);

    // Agar button URL field me "https://{{1}}" set hai (jaisa pichle template me kiya tha),
    // to yahan bhi bina https:// ke value bhejni hogi
    $buttonDynamicValue = preg_replace('#^https://#', '', $paymentUrl);

    $payload = [
        'messaging_product' => 'whatsapp',
        'recipient_type'    => 'individual',
        'to'                => $whatsappNumber,
        'type'              => 'template',
        'template'          => [
            'name'     => $templateName,
            'language' => [
                'code' => 'en'
            ],
            'components' => [
                [
                    'type'       => 'body',
                    'parameters' => [
                        ['type' => 'text', 'text' => $playerName],  // {{1}}
                        ['type' => 'text', 'text' => $paymentUrl]   // {{2}}
                    ]
                ],
                // Agar template me alag se URL button bhi hai to ye block active rakho,
                // agar body me hi text ke roop me link hai (button nahi) to ye poora block hata do.
                [
                    'type'       => 'button',
                    'sub_type'   => 'url',
                    'index'      => '0',
                    'parameters' => [
                        ['type' => 'text', 'text' => $buttonDynamicValue]
                    ]
                ]
            ]
        ]
    ];

    $apiUrl = APP_URL. $phoneNumberId . '/messages';

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL            => $apiUrl,
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS     => json_encode(
            $payload,
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        )
    ]);

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

    if ($response === false || $curlError !== '') {
        $result = [
            'success' => false,
            'error'   => $curlError ?: 'WhatsApp API request failed'
        ];
    } else {
        $result = [
            'success'   => $httpCode >= 200 && $httpCode < 300,
            'http_code' => $httpCode,
            'response'  => json_decode($response, true)
        ];
    }

    header('Content-Type: application/json');
    //echo json_encode($result, JSON_PRETTY_PRINT);
     // end whatsapp payment pending

    // if (empty($input)) {
    //     $input = [
    //         'lead_id'         => '1042',
    //         'name'            => 'Rifat Khan',
    //         'email'           => 'rifat.saleem@procorporateleague.com',
    //         'mobile'          => '9876543210',
    //         'tournament'      => 'PCL Eleven 11 - Challenger Round',
    //         'category'        => 'Individual Player',
    //         'base'            => 5000,
    //         'discount'        => 500,
    //         'gst'             => 810,
    //         'payment_pending' => false,
    //         'transaction_id'  => 'CF_TXN_20250430_9182736',
    //     ];
    // }

    $result = sendInvoiceEmail($input);

    header('Content-Type: application/json');
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}