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


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']     ?? '18 Tournament Matches';
    $category       = $data['category']       ?? '';
    $base           = (float)($data['base']           ?? 0);
    $discount       = (float)($data['discount']       ?? 0);
    $gst            = (float)($data['gst']            ?? 0);
    $adv_amount     = (float)($data['adv_amount']            ?? 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;

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

    $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', 'adv_amount',
        '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','adv_amount','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
            ))
        );

        try {
            return EmailTrackingApiClient::trackLegacy($payload);
        } catch (\Throwable $t) {
        pcl_enterprise_email_log(isset($mail) ? $mail : null, 'failed', (isset($mail) && is_object($mail) && property_exists($mail, 'ErrorInfo')) ? $mail->ErrorInfo : (isset($e) ? $e->getMessage() : 'Email sending failed'), get_defined_vars());
            return array('tracking_status' => 'failed', 'error' => $t->getMessage());
        } catch (\Exception $e) {
        pcl_enterprise_email_log(isset($mail) ? $mail : null, 'failed', (isset($mail) && is_object($mail) && property_exists($mail, 'ErrorInfo')) ? $mail->ErrorInfo : (isset($e) ? $e->getMessage() : 'Email sending failed'), get_defined_vars());
            return array('tracking_status' => 'failed', 'error' => $e->getMessage());
        }
    }
}

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('info@corporateworldcup.com', 'Corporate World Cup Info');
        $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 | 18 Tournament Matches"
        //     : "PCL Payment Confirmed | 18 Tournament Matches Registration Successful";

        $subject = "Action Required: Complete Payment to Secure Your Team Slot";
        
        $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_".$leadId."_{$invoiceNo}.pdf";
        $mail->addStringAttachment($pdfString, $pdfFilename, PHPMailer::ENCODING_BASE64, 'application/pdf');

        $mail->send();
        pcl_enterprise_email_log($mail, 'sent', '', get_defined_vars());
        return ['success' => true, 'message' => "Invoice email sent to {$email}"];

    } 
    catch (Exception $e) {
        pcl_enterprise_email_log(isset($mail) ? $mail : null, 'failed', (isset($mail) && is_object($mail) && property_exists($mail, 'ErrorInfo')) ? $mail->ErrorInfo : (isset($e) ? $e->getMessage() : 'Email sending failed'), get_defined_vars());
        return ['success' => false, 'message' => "Mailer Error: " . $mail->ErrorInfo];
    }
}


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);
    $adv_amountF = number_format($d['adv_amount'], 2);

   // echo $adv_amountF;

    //die;
    $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: The Corporate World Cup Qualification Combo Annual Package Fees<br>
                        Registration Type : {$d['category']}<br>
                        Tournament: {$d['tournament']}<br>
                        Payment: <strong>{$statusLabel}</strong>
                    </div>
                </td>
            </tr>
        </table>


         <!-- 18 matches section start -->
            <div class="section-title">18 Guaranteed Matches Across Three Premier Corporate Cricket Tournaments</div>
            <table class="line-table">
                <thead>
                    <tr>
                        <th style="width:46%;">Total 18 Matche</th>
                        <th>PCL Season 12</th>
                        <th class="right">PCL Eleven 11</th>
                        <th class="right">Test Twenty</th>]
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>18 Matches</strong></td>
                        <td class="right amount">7 Matches</td>
                        <td class="right amount">7 Matches</td>
                        <td class="right amount">4 Matches</td>
                </tbody>
            </table>
            <!-- 18 matches section end -->




        <div class="section-title">Invoice Line Items</div>
        <table class="line-table">
            <thead>
                <tr>
                    <th style="width:46%;">Item 1</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>18 Matches</strong><div class="desc-sub">7 PCL Season 12 Matches • 7 PCL Eleven 11 Matches • 4 Test Twenty Matches</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;{$gstF}</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><br>

        <!-- advance amount -->
        <div class="section-title">Advance Payment</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>Advance Payment</strong></td>
                    <td>{$d['sacCode']}</td>
                    <td class="right amount">{$adv_amountF}</td>
                    <td class="right amount">0</td>
                    <td class="right amount">0</td>
            </tbody>

        </table>
        <!-- end -->

        <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']);
    $adv_amount = htmlspecialchars($d['adv_amount']);
    $logoUrl   = PCL_LOGO_URL;
    $year      = date('Y');

    $paymentUrl = 'https://www.procorporateleague.com/pcl/team-register/teamInvoice.php?mobile=' . rawurlencode($d['mobile'])
        . '&amp;lead_id=' . rawurlencode($d['leadId'])
        . '&amp;amount=' . rawurlencode($d['adv_amount']);

    $paymentButton = '';
    if ($paymentPending) {
        $paymentButton = <<<HTML
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 24px;">
      <tr>
        <td align="center">
          <a href="{$paymentUrl}" target="_blank" style="display:inline-block;background:#123a8c;color:#ffffff;text-decoration:none;font-size:15px;font-weight:800;padding:14px 34px;border-radius:8px;box-shadow:0 5px 14px rgba(18,58,140,.22);">
            Pay Now &rarr;
          </a>
        </td>
      </tr>
    </table>
HTML;
    }



    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>

    {$paymentButton}

    <!-- 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> The Corporate World Cup Qualification Combo Annual Package Fees<br>
              <strong>Registration Type:</strong> {$d['category']}<br>
              <strong>Tournament:</strong> 18 Matches
            </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;">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: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;{$gstF}</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>

    <!-- advance payment -->
    <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;">Total Advance Amount</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;{$d['adv_amount']}</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;0</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;0</td>
      </tr>
      <tr>
        <td style="padding:14px;background:#123a8c;font-size:15px;font-weight:900;color:#fff;">Total Advance Payable</td>
        <td style="padding:14px;background:#123a8c;font-size:15px;font-weight:900;color:#efb321;text-align:right;">&#8377;{$d['adv_amount']}</td>
      </tr>
    </table>
    <!-- end -->

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

    // if (empty($input)) {
    //     $input = [
    //         'lead_id'         => '1042',
    //         'name'            => 'Rifat Khan',
    //         'email'           => 'info@corporateworldcup.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);
    // echo "<pre>"; print_r($result); die;

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