<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <style>
        @page {
            margin: 0;
        }

        body {
            font-family: 'Helvetica', 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            color: #333;
            line-height: 1.4;
            background: #fff;
        }

        .header-bar {
            background: #178bbd;
            color: #fff;
            text-align: center;
            padding: 15px 0;
            font-size: 24px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 2px;
        }

        .container {
            padding: 30px 40px;
        }

        .top-table {
            width: 100%;
            margin-bottom: 40px;
        }

        .logo-section {
            width: 50%;
            vertical-align: top;
        }

        .meta-section {
            width: 50%;
            text-align: right;
            vertical-align: top;
        }

        .logo-img {
            max-width: 180px;
            margin-bottom: 10px;
        }

        .company-info {
            font-size: 14px;
        }

        .company-name {
            font-weight: bold;
            color: #1a4a72;
            font-size: 16px;
            margin-bottom: 2px;
        }

        .invoice-id {
            font-weight: bold;
            font-size: 14px;
            margin-bottom: 20px;
            color: #333;
        }

        .balance-due-box {
            text-align: right;
        }

        .balance-due-label {
            color: #888;
            font-size: 13px;
            font-weight: bold;
        }

        .balance-due-amount {
            font-size: 22px;
            font-weight: bold;
            color: #333;
        }

        .details-table {
            width: 100%;
            margin-bottom: 40px;
        }

        .bill-to-section {
            width: 60%;
            vertical-align: top;
        }

        .billing-meta-section {
            width: 40%;
            vertical-align: top;
        }

        .section-label {
            color: #888;
            font-size: 13px;
            margin-bottom: 5px;
        }

        .customer-name {
            font-weight: bold;
            font-size: 15px;
            margin-bottom: 3px;
        }

        .customer-address {
            font-size: 13px;
            color: #666;
        }

        .billing-meta-table {
            width: 100%;
            border-collapse: collapse;
        }

        .billing-meta-table td {
            padding: 3px 0;
            font-size: 13px;
        }

        .billing-meta-label {
            text-align: right;
            padding-right: 20px !important;
            color: #888;
            width: 60%;
        }

        .billing-meta-value {
            text-align: right;
            font-weight: 500;
            width: 40%;
        }

        /* Items Table */
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }

        .items-table th {
            background: #333;
            color: #fff;
            text-align: left;
            padding: 12px 10px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .items-table td {
            padding: 15px 10px;
            border-bottom: 1px solid #eee;
            vertical-align: top;
            font-size: 13px;
        }

        .item-row {
            background: #fff;
        }

        .col-num { width: 5%; text-align: center; }
        .col-desc { width: 55%; }
        .col-qty { width: 10%; text-align: center; }
        .col-rate { width: 15%; text-align: right; }
        .col-amount { width: 15%; text-align: right; }

        .item-title {
            font-weight: bold;
            color: #333;
            margin-bottom: 4px;
            display: block;
        }

        .item-subtitle {
            font-size: 11px;
            color: #888;
        }

        /* Summary Section */
        .summary-wrapper {
            width: 100%;
        }

        .summary-table {
            width: 40%;
            float: right;
            border-collapse: collapse;
        }

        .summary-table td {
            padding: 6px 0;
            font-size: 13px;
        }

        .summary-label {
            text-align: right;
            padding-right: 30px;
            color: #666;
        }

        .summary-value {
            text-align: right;
            color: #333;
        }

        .payment-made {
            color: #e53935;
        }

        .balance-due-row {
            background: #f8f8f8;
        }

        .balance-due-row td {
            padding: 12px 0;
            border-top: 1px solid #eee;
            border-bottom: 1px solid #eee;
        }

        .balance-due-row .summary-label {
            font-weight: bold;
            color: #333;
        }

        .balance-due-row .summary-value {
            font-weight: bold;
            font-size: 16px;
        }

        .clear {
            clear: both;
        }

        .footer {
            margin-top: 60px;
            text-align: center;
            font-size: 11px;
            color: #aaa;
        }
    </style>
</head>

<body>

    <?php
        $logo = "https://yefranchisees.b-cdn.net/frontend/YoungEngineerLogo.png";

        $ch = curl_init($logo);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $data = curl_exec($ch);
        curl_close($ch);
        $type = "png";
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

        // Standardize the source of submission data
        $submissionData = $invoice->submission_data ?? $invoice->class_and_customer_details ?? [];

        $steps = [];
        $classDetails = [];
        if (is_array($submissionData)) {
            foreach ($submissionData as $index => $item) {
                if (!is_array($item)) continue;
                foreach ($item as $k => $v) {
                    if (str_starts_with($k, 'step_')) {
                        $steps[$k] = $item;
                    }
                    if ($k === 'class_details') {
                        $classDetails = $v;
                    }
                }
                if (is_numeric($index)) {
                    $num = $index + 1;
                    if (!isset($steps["step_$num"])) {
                        $steps["step_$num"] = $item;
                    }
                } else {
                    $steps[$index] = $item;
                }
            }
        }

        $findValue = function($key, $steps) {
            foreach ($steps as $step) {
                if (isset($step[$key])) return $step[$key];
            }
            return '';
        };

        $parent = $steps['step_1'] ?? [];
        $child = $steps['step_2'] ?? [];
        $group = $steps['step_3'] ?? [];
        $class = $steps['step_4'] ?? [];
        
        $programName = strip_tags($classDetails['program_name'] ?? $class['program_name'] ?? $findValue('program_name', $steps) ?: ($findValue('choose_classes', $steps) ?: ''));
        $location = $classDetails['location'] ?? $group['location'] ?? $findValue('location', $steps) ?: '';
        $instructor = $classDetails['instructor_name'] ?? $class['instructor_name'] ?? $findValue('instructor_name', $steps) ?: '';
        $startDate = $classDetails['start_date'] ?? $class['start_date'] ?? $findValue('start_date', $steps) ?: '';
        $startTime = $classDetails['start_time'] ?? $class['start_time'] ?? $findValue('start_time', $steps) ?: '';
        $endTime = $classDetails['end_time'] ?? $class['end_time'] ?? $findValue('end_time', $steps) ?: '';
        $ageMin = $classDetails['min_age'] ?? $class['min_age'] ?? $findValue('min_age', $steps) ?: '0';
        $ageMax = $classDetails['max_age'] ?? $class['max_age'] ?? $findValue('max_age', $steps) ?: '99';

        $companyName = $classDetails['company_name'] ?? '';
        $companyAddress = $classDetails['company_address'] ?? '';

        // Financial fields — invoice total is the amount actually charged (e.g. first installment).
        // $taxRate is a percentage (e.g. 8 for 8%). Never fall back to $invoice->tax here because
        // that field stores a dollar amount, not a rate.
        $taxRate  = (float)($classDetails['invoice_tax_value'] ?? 0);
        $taxLabel = $classDetails['invoice_tax_label'] ?? 'Tax';

        // $invoice may be a PaymentInvoice (has ->total) or a FormSubmission (does not).
        // Fall back to step-3 payment fields when the model field is absent.
        $total = (float)(
            $invoice->total                   // PaymentInvoice — authoritative value
            ?? $group['final_price']          // FormSubmission fallback: step_3 field
            ?? $group['amount_due_now']       // FormSubmission fallback: alternate step_3 field
            ?? $invoice->amount               // legacy alias
            ?? 0
        );

        // $invoice->tax stores the actual dollar amount (set by PaymentAmountResolver).
        $taxAmount = (float)($invoice->tax ?? 0);
        if ($total > 0 && $taxAmount <= 0 && $taxRate > 0) {
            $taxAmount = round($total * ($taxRate / (100 + $taxRate)), 2);
        }
        $subtotal = max(0, $total - $taxAmount);

        // Per-unit price / lesson count: prefer class_details (populated after Fix 1),
        // fall back to step-3 keys sent by the frontend for older submissions.
        $perUnitPrice = (float)($classDetails['price'] ?? $group['per_unit_price'] ?? 0);
        $lessonCount  = max(1, (int)($classDetails['number_of_lessons'] ?? $group['number_of_lessons'] ?? 1));
        $totalProgramPrice = (float)($classDetails['total_class_value'] ?? $classDetails['total_program_price'] ?? $group['total_class_value'] ?? 0);
        if ($totalProgramPrice <= 0 && $perUnitPrice > 0) {
            $totalProgramPrice = $perUnitPrice * $lessonCount;
        }
        $installmentLabel = '';
        $paymentStep = $steps['step_3'] ?? [];
        if (!empty($paymentStep['installment_number']) && !empty($paymentStep['installment_total'])) {
            $installmentLabel = ' (Payment '.$paymentStep['installment_number'].' of '.$paymentStep['installment_total'].')';
        }

        $paymentFrequency = strtolower((string)($classDetails['payment_charges_frequency'] ?? $paymentStep['payment_charges_frequency'] ?? ''));
        $frequencyLabel = match ($paymentFrequency) {
            'weekly' => 'Weekly',
            'monthly' => 'Monthly',
            'daily' => 'Daily',
            'per_lesson' => 'Per lesson',
            default => $paymentFrequency !== '' ? ucfirst(str_replace('_', ' ', $paymentFrequency)) : '',
        };
        $feeBasis = strtolower((string)($classDetails['price_name'] ?? $classDetails['fee_basis'] ?? 'per_lesson'));
        $priceSuffix = str_contains($feeBasis, 'month') ? 'per month' : (str_contains($feeBasis, 'week') ? 'per week' : 'per lesson');

        $parentEmail = $parent['email'] ?? $findValue('email', $steps) ?: '';

        $currency = strtoupper($invoice->currency ?? 'USD');
        $currencySymbol = ($currency === 'USD') ? '$' : $currency . ' ';

        $isPaid = (strtolower($invoice->status ?? '') === 'paid');
        $paymentMade = $isPaid ? $total : 0;
        $balanceDue = $total - $paymentMade;

        $invoiceDate = $invoice->paid_at
            ? $invoice->paid_at->format('F d, Y')
            : ($invoice->created_at ? $invoice->created_at->format('F d, Y') : now()->format('F d, Y'));
        $dueDate = $invoiceDate;
        $terms = "Due on Receipt";

        // Invoice Number logic
        $invoiceNum = $invoice->id;
        // If there's a UUID or reference number, we could use it here. 
        // For now using the ID to keep it functional.
    ?>

    <div class="header-bar">
        INVOICE
    </div>

    <div class="container">
        <!-- Top Section -->
        <table class="top-table">
            <tr>
                <td class="logo-section">
                    <img src="<?php echo e($base64); ?>" class="logo-img">
                    <div class="company-info">
                        <?php if($companyName): ?>
                            <div class="company-name"><?php echo e($companyName); ?></div>
                        <?php endif; ?>
                        <?php if($companyAddress): ?>
                            <div class="company-address"><?php echo e($companyAddress); ?></div>
                        <?php endif; ?>
                    </div>
                </td>
                <td class="meta-section">
                    <div class="invoice-id"># <?php echo e($invoice->uuid ?? $invoice->id); ?></div>
                    <div class="balance-due-box">
                        <div class="balance-due-label">Balance Due</div>
                        <div class="balance-due-amount"><?php echo e($currencySymbol); ?><?php echo e(number_format($balanceDue, 2)); ?></div>
                    </div>
                </td>
            </tr>
        </table>

        <!-- Billing Info -->
        <table class="details-table">
            <tr>
                <td class="bill-to-section">
                    <div class="section-label">Bill To</div>
                    <div class="customer-name"><?php echo e($parent['name'] ?? $findValue('name', $steps)); ?></div>
                    <div class="customer-address">
                        <?php if($parentEmail): ?>
                            <?php echo e($parentEmail); ?><br>
                        <?php endif; ?>
                        Child: <?php echo e($child['childs_name'] ?? $findValue('childs_name', $steps)); ?>

                    </div>
                </td>
                <td class="billing-meta-section">
                    <table class="billing-meta-table">
                        <tr>
                            <td class="billing-meta-label">Invoice Date :</td>
                            <td class="billing-meta-value"><?php echo e($invoiceDate); ?></td>
                        </tr>
                        <tr>
                            <td class="billing-meta-label">Terms :</td>
                            <td class="billing-meta-value"><?php echo e($terms); ?></td>
                        </tr>
                        <tr>
                            <td class="billing-meta-label">Due Date :</td>
                            <td class="billing-meta-value"><?php echo e($dueDate); ?></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>

        <!-- Items Table -->
        <table class="items-table">
            <thead>
                <tr>
                    <th class="col-num">#</th>
                    <th class="col-desc">Item & Description</th>
                    <th class="col-qty">Qty</th>
                    <th class="col-rate">Rate</th>
                    <th class="col-amount">Amount</th>
                </tr>
            </thead>
            <tbody>
                <tr class="item-row">
                    <td class="col-num">1</td>
                    <td class="col-desc">
                        <span class="item-title"><?php echo e($programName); ?><?php echo e($installmentLabel); ?></span>
                        <span class="item-subtitle">
                            Child: <?php echo e($child['childs_name'] ?? $findValue('childs_name', $steps)); ?>

                            <?php if($lessonCount > 0): ?>
                                · <?php echo e($lessonCount); ?> lessons
                            <?php endif; ?>
                            <?php if($perUnitPrice > 0): ?>
                                · Unit price <?php echo e($currencySymbol); ?><?php echo e(number_format($perUnitPrice, 2)); ?> <?php echo e($priceSuffix); ?>

                            <?php endif; ?>
                        </span>
                    </td>
                    <td class="col-qty">1.00</td>
                    <td class="col-rate"><?php echo e(number_format($subtotal, 2)); ?></td>
                    <td class="col-amount"><?php echo e(number_format($subtotal, 2)); ?></td>
                </tr>
            </tbody>
        </table>

        <!-- Summary Section -->
        <div class="summary-wrapper">
            <table class="summary-table">
                <tr>
                    <td class="summary-label">Subtotal:</td>
                    <td class="summary-value"><?php echo e($currencySymbol); ?><?php echo e(number_format($subtotal, 2)); ?></td>
                </tr>
                <?php if($taxRate > 0): ?>
                <tr>
                    <td class="summary-label"><?php echo e(strtolower($taxLabel)); ?> (<?php echo e($taxRate); ?>%):</td>
                    <td class="summary-value"><?php echo e($currencySymbol); ?><?php echo e(number_format($taxAmount, 2)); ?></td>
                </tr>
                <?php endif; ?>
                <tr>
                    <td class="summary-label">Total:</td>
                    <td class="summary-value"><?php echo e($currencySymbol); ?><?php echo e(number_format($total, 2)); ?></td>
                </tr>
                <tr>
                    <td class="summary-label">Payment Made:</td>
                    <td class="summary-value payment-made">(-) <?php echo e($currencySymbol); ?><?php echo e(number_format($paymentMade, 2)); ?></td>
                </tr>
                <tr class="balance-due-row">
                    <td class="summary-label">Balance Due:</td>
                    <td class="summary-value"><?php echo e($currencySymbol); ?><?php echo e(number_format($balanceDue, 2)); ?></td>
                </tr>
            </table>
            <div class="clear"></div>
        </div>

        <div class="footer">
            Thank you for choosing our programs.
        </div>
    </div>

</body>
</html>
<?php /**PATH /home/org/public_html/backend.youngengineers.org/resources/views/pdf/invoice.blade.php ENDPATH**/ ?>