<?php
    $invConfig = session('company.invoice_configuration') ? json_decode(session('company.invoice_configuration'), true) : [];
    $outletStateCode = $sale->outlet && $sale->outlet->state ? ($sale->outlet->state->state_code ?? null) : null;
    $customerStateCode = $sale->customer && $sale->customer->state ? ($sale->customer->state->state_code ?? null) : null;
    $isIntraState = ($customerStateCode === null) || ($outletStateCode === null) || ($customerStateCode === $outletStateCode);
    $vatObjects = $sale->sale_vat_objects ? json_decode($sale->sale_vat_objects, true) : [];
    $vatObjects = is_array($vatObjects) ? $vatObjects : [];
    $summaryTaxes = [];
    foreach ($vatObjects as $v) {
        $taxName = $v['tax_field_type'] ?? $v['tax_field_name'] ?? '';
        if (!$taxName) continue;
        $amt = (float) ($v['tax_field_amount'] ?? 0);
        $pct = (float) ($v['tax_field_percentage'] ?? 0);
        if (!isset($summaryTaxes[$taxName])) {
            $summaryTaxes[$taxName] = ['amount' => 0, 'rate' => $pct];
        }
        $summaryTaxes[$taxName]['amount'] += $amt;
        if ($pct > 0 && $summaryTaxes[$taxName]['rate'] == 0) {
            $summaryTaxes[$taxName]['rate'] = $pct;
        }
    }
    $defaultHsn = $invConfig['default_hsn_code'] ?? '0000';
    $totalItemDiscount = 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(__('Sale No')); ?>: <?php echo e($sale->sale_no); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo e(asset('public/backend_assets/css/invoice-all.css')); ?>" />
</head>
<body class="invoice-56mm">
    <!-- HEADER -->
    <table class="header-table">
        <tr>
            <td class="company-info">
                <?php $invoice_logo = session('company.invoice_logo'); ?>
                <?php if($invoice_logo): ?>
                    <img src="<?php echo e(asset('public/uploads/site_settings/' . $invoice_logo)); ?>" alt="Logo" class="logo">
                <?php endif; ?>
                <h2 class="heading-title"><?php echo e(session('company.business_name', '')); ?></h2>
                <?php if($sale->outlet): ?>
                    <p>Outlet: <?php echo e($sale->outlet->outlet_name ?? ''); ?></p>
                    <p>Phone: <?php echo e($sale->outlet->phone ?? ''); ?></p>
                    <p>Email: <?php echo e($sale->outlet->email ?? ''); ?></p>
                    <p>Address: <?php echo e($sale->outlet->address ?? ''); ?></p>
                    <?php if(isEnableGST() && session('company.collect_tax') == 'Yes'): ?>
                        <?php if($sale->outlet->state && ($sale->outlet->state->state_name || $sale->outlet->state->state_code)): ?>
                            <p><?php echo e(__('Outlet State')); ?>: <?php echo e($sale->outlet->state->state_name ?? ''); ?> (<?php echo e($sale->outlet->state->state_code ?? ''); ?>)</p>
                        <?php endif; ?>
                        <?php if($sale->outlet->gstin): ?>
                            <p><?php echo e(__('Outlet GSTIN')); ?>: <?php echo e($sale->outlet->gstin); ?></p>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php endif; ?>
            </td>
        </tr>
    </table>

    <!-- CUSTOMER + SALE INFO -->
    <table class="customer-sale-info" style="margin-top:10px">
        <tr>
            <td width="50%" valign="top">
                <div class="heading-title"><?php echo e(__('Customer')); ?></div>
                <table class="info-table">
                    <?php if($sale->customer): ?>
                        <?php if($sale->customer->name): ?>
                        <tr><td><?php echo e(__('Name')); ?></td><td>: <?php echo e($sale->customer->name); ?></td></tr>
                        <?php endif; ?>
                        <?php if($sale->customer->phone): ?>
                        <tr><td><?php echo e(__('Phone')); ?></td><td>: <?php echo e($sale->customer->phone); ?></td></tr>
                        <?php endif; ?>
                        <?php if($sale->customer->email): ?>
                        <tr><td><?php echo e(__('Email')); ?></td><td>: <?php echo e($sale->customer->email); ?></td></tr>
                        <?php endif; ?>
                        <?php if($sale->customer->address): ?>
                        <tr><td><?php echo e(__('Address')); ?></td><td>: <?php echo e($sale->customer->address); ?></td></tr>
                        <?php endif; ?>
                        <?php if(isEnableGST() && session('company.collect_tax') == 'Yes'): ?>
                            <?php if($sale->customer->gst_number): ?>
                            <tr><td><?php echo e(__('GSTIN')); ?></td><td>: <?php echo e($sale->customer->gst_number); ?></td></tr>
                            <?php endif; ?>
                            <?php if($sale->customer->state && ($sale->customer->state->state_name || $sale->customer->state->state_code)): ?>
                            <tr><td><?php echo e(__('Customer State')); ?></td><td>: <?php echo e($sale->customer->state->state_name ?? ''); ?> (<?php echo e($sale->customer->state->state_code ?? ''); ?>)</td></tr>
                            <?php endif; ?>
                        <?php endif; ?>
                    <?php else: ?>
                        <tr><td><?php echo e(__('Name')); ?></td><td>: <?php echo e(__('Walk-in Customer')); ?></td></tr>
                    <?php endif; ?>
                </table>
            </td>
            <td width="50%" valign="top">
                <div class="heading-title"><?php echo e(__('Sale')); ?></div>
                <table class="info-table">
                    <?php if($sale->sale_no): ?>
                    <tr><td><?php echo e(__('Sale No')); ?></td><td>: <?php echo e($sale->sale_no); ?></td></tr>
                    <?php endif; ?>
                    <?php
                        // Compute DateTime string as "YYYY/MM/DD h:iA"
                        $dateTimeString = null;
                        if (!empty($sale->date_time)) {
                            $date = \Carbon\Carbon::parse($sale->date_time);
                            $dateTimeString = $date->format('Y/m/d g:ia');
                            $dateTimeString = strtoupper(substr($dateTimeString, 0, -2)) . ' ' . substr($dateTimeString, -2); // Make AM/PM uppercase
                        } elseif (!empty($sale->sale_date)) {
                            // Fallback to sale_date without time
                            $date = \Carbon\Carbon::parse($sale->sale_date);
                            $dateTimeString = $date->format('Y/m/d');
                        }
                    ?>
                    <?php if(!empty($dateTimeString)): ?>
                    <tr><td><?php echo e(__('Date Time')); ?></td><td>: <?php echo e($dateTimeString); ?></td></tr>
                    <?php endif; ?>
                    <?php if($sale->employee): ?>
                    <tr><td><?php echo e(__('Sales By')); ?></td><td>: <?php echo e($sale->employee->name); ?></td></tr>
                    <?php endif; ?>
                    <tr><td><?php echo e(__('Status')); ?></td><td>: <?php echo e($sale->due_amount > 0 ? __('Due') : __('Paid')); ?></td></tr>
                </table>
            </td>
        </tr>
    </table>

    <!-- ITEMS TABLE -->
    <table class="items-table" style="margin-top:10px">
        <thead>
            <tr>
                <th width="5%">#</th>
                <?php if(isEnableGST() && isset($invConfig['show_hsn_code']) && $invConfig['show_hsn_code'] == 'Yes'): ?>
                <th width="6%"><?php echo e(__('HSN')); ?></th>
                <?php endif; ?>
                <th width="<?php echo e(isEnableGST() && isset($invConfig['show_hsn_code']) && $invConfig['show_hsn_code'] == 'Yes' ? '22%' : '25%'); ?>"><?php echo e(__('Item')); ?></th>
                <th width="15%"><?php echo e(__('IMEI/Serial')); ?></th>
                <th width="8%"><?php echo e(__('Qty')); ?></th>
                <th width="12%"><?php echo e(__('Unit Price')); ?></th>
                <th width="12%"><?php echo e(__('Total')); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php $i = 0; ?>
            <?php if($sale->saleDetails && $sale->saleDetails->count() > 0): ?>
                <?php $__currentLoopData = $sale->saleDetails; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $detail): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php
                        $i++;
                        $lineSubtotal = $detail->qty * $detail->menu_price_with_discount;
                        $lineTotal = $lineSubtotal;
                        $detailTaxDisplay = '';
                        $itemTaxType = $detail->item && $detail->item->tax_type ? $detail->item->tax_type : 'Inclusive';
                        $menuTaxes = $detail->menu_taxes ? json_decode($detail->menu_taxes, true) : [];
                        $menuTaxes = is_array($menuTaxes) ? $menuTaxes : [];
                        foreach ($menuTaxes as $t) {
                            $name = $t['tax_field_name'] ?? $t['tax_field_type'] ?? '';
                            $amt = (float) ($t['tax_field_amount'] ?? 0);
                            $pct = (float) ($t['tax_field_percentage'] ?? 0);
                            if ($name && $amt > 0) {
                                $detailTaxDisplay .= ($detailTaxDisplay ? ', ' : '') . $name . ($pct > 0 ? ' ' . $pct . '%' : '') . ' - ' . formatAmount($amt);
                            }
                        }
                        if ($detailTaxDisplay && !$isIntraState) {
                            $detailTaxDisplay .= ' (' . __($itemTaxType) . ')';
                        }
                        $hsnCode = ($detail->item && $detail->item->hsn_code) ? $detail->item->hsn_code : ($defaultHsn ?? '0000');
                    ?>
                    <tr>
                        <td><?php echo e($i); ?></td>
                        <?php if(isEnableGST() && isset($invConfig['show_hsn_code']) && $invConfig['show_hsn_code'] == 'Yes'): ?>
                        <td><?php echo e($hsnCode); ?></td>
                        <?php endif; ?>
                        <td>
                            <?php if($detail->item): ?>
                                <?php if($detail->item->parent_id && $detail->item->parent): ?>
                                    <?php echo e($detail->item->parent->name); ?> - <?php echo e($detail->item->name); ?>

                                <?php else: ?>
                                    <?php echo e($detail->item->name); ?>

                                <?php endif; ?>
                                <?php if($detail->item->code): ?>
                                    (<?php echo e($detail->item->code); ?>)
                                <?php endif; ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if($detail->expiry_imei_serial): ?>
                                <?php if($detail->item && in_array($detail->item->type, ['IMEI_Product', 'Serial_Product'])): ?>
                                    <?php echo e($detail->item->type === 'IMEI_Product' ? 'IMEI' : 'Serial'); ?>: <?php echo e($detail->expiry_imei_serial); ?>

                                <?php elseif($detail->item && $detail->item->type === 'Medicine_Product'): ?>
                                    <?php echo e($detail->expiry_imei_serial); ?>

                                <?php else: ?>
                                    <?php echo e($detail->expiry_imei_serial); ?>

                                <?php endif; ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td class="num"><?php echo e($detail->qty); ?></td>
                        <td class="num"><?php echo e(formatAmount($detail->menu_unit_price)); ?></td>
                        <td class="num"><?php echo e(formatAmount($lineTotal)); ?></td>
                    </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- SUMMARY -->
    <table style="margin-top:10px">
        <tr>
            <td valign="top">
                <table class="summary-table">
                    <tr>
                        <td><?php echo e(__('Subtotal')); ?></td>
                        <td><?php echo e(formatAmount($sale->sub_total)); ?></td>
                    </tr>
                    <?php if(isset($sale->total_item_discount_amount) && $sale->total_item_discount_amount > 0): ?>
                    <tr>
                        <td><?php echo e(__('Item Discount')); ?></td>
                        <td><?php echo e(formatAmount($sale->total_item_discount_amount)); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if(isset($sale->sub_total_discount_amount) && $sale->sub_total_discount_amount > 0): ?>
                    <tr>
                        <td><?php echo e(__('Order Discount')); ?></td>
                        <td><?php echo e(formatAmount($sale->sub_total_discount_amount)); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if($sale->total_discount_amount > 0 && !isset($sale->total_item_discount_amount) && !isset($sale->sub_total_discount_amount)): ?>
                    <tr>
                        <td><?php echo e(__('Discount')); ?></td>
                        <td><?php echo e(formatAmount($sale->total_discount_amount)); ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php $__currentLoopData = $summaryTaxes ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $taxName => $taxData): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php if(($taxData['amount'] ?? 0) > 0): ?>
                    <tr>
                        <td><?php echo e($taxName); ?><?php echo e(($taxData['rate'] ?? 0) > 0 ? ' (' . $taxData['rate'] . '%)' : ''); ?></td>
                        <td><?php echo e(formatAmount($taxData['amount'])); ?></td>
                    </tr>
                        <?php endif; ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <?php if($sale->delivery_charge > 0): ?>
                    <tr>
                        <td><?php echo e(__('Delivery Charge')); ?></td>
                        <td><?php echo e(formatAmount($sale->delivery_charge)); ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr class="grand-total">
                        <td><?php echo e(__('Grand Total')); ?></td>
                        <td><?php echo e(formatAmount($sale->total_payable ?? $sale->grand_total)); ?></td>
                    </tr>
                    <tr>
                        <td><?php echo e(__('Paid Amount')); ?></td>
                        <td><?php echo e(formatAmount($sale->paid_amount)); ?></td>
                    </tr>
                    <tr>
                        <td><?php echo e(__('Due Amount')); ?></td>
                        <td><?php echo e(formatAmount($sale->due_amount)); ?></td>
                    </tr>
                    <?php if(isset($invConfig['show_payment_method']) && $invConfig['show_payment_method'] == 'Yes' && $sale->salePayments && $sale->salePayments->count() > 0): ?>
                    <tr>
                        <td><?php echo e($invConfig['payment_method_label'] ?? __('Payment Method')); ?></td>
                        <td></td>
                    </tr>
                    <?php $__currentLoopData = $sale->salePayments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $payment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <tr>
                        <td><?php echo e($payment->paymentMethod->name ?? __('Cash')); ?></td>
                        <td><?php echo e(formatAmount($payment->amount)); ?></td>
                    </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <?php endif; ?>
                </table>
            </td>
        </tr>
    </table>

    <!-- FOOTER -->
    <?php if(session('company.term_conditions')): ?>
    <div class="footer">
        <?php echo session('company.term_conditions'); ?>

    </div>
    <?php endif; ?>
    
    <?php if(session('company.invoice_footer')): ?>
    <div class="footer">
        <?php echo session('company.invoice_footer'); ?>

    </div>
    <?php endif; ?>

    
    
    <?php if($sale->zatca_phase1_qr_code): ?>
    <?php
        $qrData = base64_decode($sale->zatca_phase1_qr_code);
        $qrDataEncoded = urlencode($qrData);
        $qrCodeImageUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=' . $qrDataEncoded;
    ?>
    <div style="text-align: center; margin-top: 20px;">
        <p style="font-weight: 600; margin-bottom: 10px;"><?php echo e(__('ZATCA QR Code')); ?></p>
        <img src="<?php echo e($qrCodeImageUrl); ?>" alt="ZATCA QR Code" style="max-width: 150px; height: auto;">
    </div>
    <?php endif; ?>

    <div style="text-align: center; margin-top: 30px;">
        <!-- add tailwind button class -->
        <button onclick="window.print();" type="button" class="print-btn px-6 py-3 rounded-xl bg-indigo-600 text-white font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"><?php echo e(__('Print')); ?></button>
    </div>

    <script>
        window.onload = function () {
            window.print();
        };
    </script>
</body>
</html>
<?php /**PATH D:\xampp-8.2\htdocs\off_pos_laravel\Modules/Sale\resources/views/sale/56mm-invoice.blade.php ENDPATH**/ ?>