<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('assets/css/style.css')); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('assets/css/bootstrap.min.css')); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('assets/css/soft-ui-dashboard.css')); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('assets/css/soft-ui-dashboard.min.css')); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('assets/css/soft-ui-dashboard.css.map')); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('assets/css/nucleo-svg.css')); ?>">
    <title>Invoice</title>
    <style>
        /* Basic reset */
        body,
        html {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-color: rgb(253, 253, 253) !important;
            color: black !important;
        }

        /* Thermal printer page size */
        .invoice-wrapper {
            width: 80mm;
            /* Thermal printer width */
            margin: 0 auto;
            padding: 5mm;
            font-size: 12px;
        }

        /* Centering content */
        .header {
            text-align: center;
        }

        .invoice-logo img {
            width: 70%;
            /* Adjust logo to fit thermal print */
            max-width: 100%;
            object-fit: contain;
        }

        .invoice-title {
            font-size: 14px;
            font-weight: bold;
            margin-top: 2mm;
        }

        /* Invoice From / To Table */
        .info-section {
            margin-top: 10mm;
        }

        .info-section table {
            width: 100%;
            border: none;
            margin-top: 5mm;
        }

        .info-section td {
            padding: 2mm 0;
        }

        .info-section h4 {
            font-size: 14px;
            margin-bottom: 2mm;
        }

        .info-section p {
            font-size: 12px;
            margin: 2px 0;
        }

        /* Table styles for item details */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 5mm;
            table-layout: fixed;
        }

        table th,
        table td {
            font-size: 12px;
            padding: 2mm;
            text-align: left;
        }

        table th {
            background-color: #f2f2f2;
        }

        table td {
            text-align: right;
        }

        /* Total Section */
        .total-section td {
            font-weight: bold;
        }

        /* Footer Note */
        .footer-note {
            font-size: 8px;
            color: #888;
            margin-top: 10mm;
            text-align: center;
        }

        .greeting {
            text-align: center;
            margin-top: 10px;

        }

        .greeting-text {
            font-size: small;
            font-weight: bold;
            margin-bottom: 0px;
        }

        /* Hide buttons during print */
        @media print {
            .invoice-btn-section {
                display: none;
            }
        }

        /* Print settings for thermal printer */
        @media print {
            body {
                margin: 0;
                padding: 0;
                font-size: 12px;
            }

            .invoice-wrapper {
                width: 80mm;
                page-break-before: always;
            }

            /* Make sure text is properly aligned for printing */
            .info-section {
                margin-top: 10mm;
            }

            .info-section table {
                width: 100%;
            }

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

        }

        .form-select {
            margin-bottom: 1rem !important;
        }
    </style>
</head>

<body>

    <div class="invoice-wrapper" id="invoice_wrapper">
        <!-- Header with logo and invoice title -->
        <div class="header">
            <div class="invoice-logo">
                <img src="<?php echo e(getFileUrl($settings->logo ? $settings->logo : 'storage/logo/logo_invoice.png')); ?>"
                    alt="logo">
            </div>
            <div class="invoice-title">Invoice #<?php echo e($addedInvoice->invoice_id ?? ''); ?></div>
            <?php if($addedInvoice->gst == 'Y'): ?>
            <div class="invoice-title">GST No :<?php echo e($settings->gst_no ?? ''); ?></div>
            <?php endif; ?>
            <div class="invoice-title">Invoice Date:
                <?php echo e($addedInvoice->invoice_date ? \Carbon\Carbon::parse($addedInvoice->invoice_date)->format('d-m-Y') : ''); ?>

            </div>
        </div>

        <!-- Sender/Receiver Information in Table format -->
        <?php if($settings->is_header == 'A'): ?>
            <div class="info-section">
                <table style="width: 100%; border: none;">
                    <tr>
                        <td style="text-align: left; vertical-align: top; padding-right: 10px;">
                            <h4>Invoice From:</h4>
                            <p><?php echo e($settings->company_name ?? ''); ?></p>
                            <p><?php echo e($settings->address ?? ''); ?></p>
                            <p><?php echo e($settings->email ?? ''); ?></p>
                            <p>(+91) <?php echo e($settings->phone ?? ''); ?></p>
                        </td>
                        <td style="text-align: left; vertical-align: top;">
                            <h4>Invoice To:</h4>
                            <p><?php echo e($addedInvoice->client->user->name ?? ''); ?></p>
                            <p>(+91) <?php echo e($addedInvoice->client->user->phone ?? ''); ?></p><br>
                            <?php
                                $address = optional(optional($addedInvoice->order)->clientAddress)->address
                                    ?? optional(optional($addedInvoice->client)->user)->location
                                    ?? '';
                            ?>
                            <?php echo e($address ?? ''); ?>

                        </td>
                    </tr>
                </table>
            </div>
        <?php endif; ?>

        <!-- Invoice Details Table -->
        <table style="width:100%">
            <thead>
                <tr>
                    <th style="width:10%">No.</th>
                    <th style="width:40%">Item</th>
                    <th style="width:20%">Price</th>
                    <th style="width:10%">Qty</th>
                    <th style="width:20%">Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php
                    $sumQty = 0;
                    $totalTax = 0;
                    $subtotal = 0;                  

                ?>

                <?php $__currentLoopData = $addedInvoice->invoiceItems; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $data): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <tr>
                            <td><?php echo e($index + 1); ?></td>
                            <td style="text-align: left; font-weight:bold;">
                                <?php echo e($settings->native_name_flag == 'A' ? ($data->products->native_name ?? $data->product_name) : ($data->product_name ?? '')); ?>

                            </td>

                    <?php
                        $productTax = 0;
                        $price = $data->price;
                        $rowTotal = 0;

                        // Check if price includes tax and GST is applicable
                        if ($settings->price_tax_flag == 'A' && $addedInvoice->gst != 'N') {
                            if (!empty($data->invoiceItemTaxes)) {
                                foreach ($data->invoiceItemTaxes as $tax) {
                                    $productTax += ($data->price * $tax->tax) / 100;
                                }
                            }

                            $price += $productTax;
                            $totalTax += $productTax;
                        }

                        // Calculate row total
                        $rowTotal = $price * $data->quantity;
                        $subtotal += $rowTotal;
                    ?>

                            <td><?php echo e(number_format($price ?? 0, 2)); ?></td>
                            <td><?php echo e($data->quantity ?? 0); ?></td>
                            <td><?php echo e(number_format($rowTotal ?? 0, 2)); ?></td>
                        </tr>

                        <?php $sumQty += $data->quantity ?? 0; ?>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>


                
                <tr>
                    <td colspan="4" style="text-align: right;">SubTotal</td>
                    <?php if($settings->price_tax_flag == 'A'): ?>
                        <td>₹<?php echo e(number_format($subtotal ?? 0, 2)); ?></td>
                    <?php else: ?>
                        <td>₹<?php echo e(number_format($addedInvoice->amount ?? 0, 2)); ?></td>
                    <?php endif; ?>
                </tr>

                
                <?php if($settings->price_tax_flag != 'A'): ?>
                    <?php                    
                                                                        foreach ($addedInvoice->invoiceItems as $item) {
                            if (!empty($item->invoiceItemTaxes)) {
                                foreach ($item->invoiceItemTaxes as $tax) {
                                    $totalTax += ($item->total * $tax->tax) / 100;
                                }
                            }
                        }
                    ?>
                                <tr>
                                     <td colspan="4" style="text-align: right;">Tax</td
                       >               
                                <td>₹<?php echo e(number_format($totalTax, 2)); ?></td>
                                    </tr>
                <?php endif; ?>
    
            <?php
                $totalDiscount = 0;
                $totalBeforeDiscount = $settings->price_tax_flag == 'A'
                    ? $subtotal
                    : ($addedInvoice->amount ?? 0) + $totalTax;

                if ($addedInvoice->discount_type == 1) {
                    $totalDiscount = $addedInvoice->discount ?? 0;
                } elseif ($addedInvoice->discount_type == 2) {
                    $totalDiscount = ($totalBeforeDiscount * ($addedInvoice->discount ?? 0)) / 100;
                }
            ?>
                <tr>
                <td colspan="4" style="text-align: right;">Discount</td>
        <td>₹<?php echo e(number_format($totalDiscount, 2)); ?></td>
    </tr>
    
                <?php
                    $redeemed = ($settings->loyalty_config == 'A') ? ($redeemed_value ?? 0) : 0;
                ?>
                <?php if($settings->loyalty_config == 'A'): ?>
                    <tr>
                                <td colspan="4" style="text-align: right;">Redeemed Amount</td>
                                <td>₹<?php echo e(number_format($redeemed, 2)); ?></td>
                            </tr>
                <?php endif; ?>

                
                <?php
                    $grandTotal = floor($totalBeforeDiscount - $totalDiscount - $redeemed);
                ?>
                <tr>
                    <td colspan="4" style="text-align: right;">Grand Total</td>
                    <td><strong>₹<?php echo e(number_format($grandTotal, 2)); ?></strong></td>
                </tr>

                
                <tr>
                    <td colspan="4" style="text-align: right;">Total Purchased Product Qty</td>
                    <td><strong><?php echo e($sumQty); ?></strong></td>
                </tr>
                <tr>
                    <td colspan="4" style="text-align: right;">Due Amount</td>
                    <td><strong>₹<?php echo e(number_format($dueAmount ?? 0,2)); ?></strong></td>
                </tr>
            </tbody>

        </table>

        <!-- Footer Note -->
        <div class="greeting">
            <p class="greeting-text">Thank you! Visit again.</p>
    </div>

        <!-- Print/Download Buttons (visible only in normal view, not in print) -->
        <div class="invoice-btn-section">
            <div class="d-flex gap-2 ">
                <select name="paper_size" id="paper_size" class="form-select">
                        <option value="">Select Standard paper size</option>
                        <?php $__currentLoopData = $paper; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($item->id); ?>"><?php echo e($item->name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </div>
            <div class="d-flex gap-2">
                <a href="javascript:window.print()" class="btn">
            <i class="fa fa-print"></i> Print Invoice
        </a>
        <a id="invoice_download_btn" class="btn">
                    <i class="fa fa-download"></i> Download Invoice
                </a>
            </div>
            <div class="d-flex gap-2">
                <?php if($settings->whatsapp_config == 'A'): ?>
                    <a href="#" id="send_invoice" class="btn">
                        <i class="fa-brands fa-whatsapp"></i>Send Invoice
                    </a>
                <?php endif; ?>
                <a href='<?php echo e(route('invoice-index')); ?>' id="cancel-btn" class="btn">
                    <i class="fa fa-arrow-left"></i> Back
                </a>
            </div>

        </div>
    </div>

    <!-- JS Scripts for Downloading as PDF -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="<?php echo e(asset('assets/js/jspdf.min.js')); ?>"></script>
    <script src="<?php echo e(asset('assets/js/html2canvas.js')); ?>"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        $(function () {
            $(document).on('click', '#invoice_download_btn', function () {

                $(".invoice-btn-section").hide();

                var content = $("#invoice_wrapper");

                // Step 1: Apply temporary scale-down before capturing
                content.css({
                    transform: 'scale(0.95)',
                    transformOrigin: 'top left'
                });

                // Allow DOM to update before canvas capture
                setTimeout(function () {

                    var contentElement = content[0];

                    var contentWidth = contentElement.offsetWidth;
                    var contentHeight = contentElement.offsetHeight;

                    var pdfWidth = 80; // Thermal printer width in mm
                    var pdfHeight = (contentHeight * pdfWidth) / contentWidth;

                    html2canvas(contentElement, {
                        allowTaint: true,
                        scale: 2,
                        useCORS: true
                    }).then(function (canvas) {

                        var imgData = canvas.toDataURL("image/jpeg", 1.0);
                        var pdf = new jsPDF('p', 'mm', [pdfWidth, pdfHeight]);

                        pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight);
                        pdf.save("<?php echo e($addedInvoice->invoice_id); ?>.pdf");

                        // Step 3: Reset the scale after PDF generation
                        content.css({
                            transform: '',
                            transformOrigin: ''
                        });

                        $(".invoice-btn-section").show();
                    });

                }, 300); // slight delay to ensure transform is applied

            });
        });
    </script>


    <script>
        $(function () {
            $(document).on('click', '#send_invoice', function () {
                $(".invoice-btn-section").hide();

                var content = $("#invoice_wrapper")[0];
                var contentWidth = content.offsetWidth;
                var contentHeight = content.offsetHeight;
                var pdfWidth = 80;
                var pdfHeight = (contentHeight * pdfWidth) / contentWidth;

                html2canvas(content, {
                    allowTaint: true,
                    scale: 2,
                    useCORS: true
                }).then(function (canvas) {
                    var imgData = canvas.toDataURL("image/jpeg", 1.0);
                    var pdf = new jsPDF('p', 'mm', [pdfWidth, pdfHeight]);
                    pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight);

                    var pdfBlob = pdf.output('blob');
                    var formData = new FormData();
                    formData.append("invoice_pdf", pdfBlob, "invoice_<?php echo e($addedInvoice->invoice_id); ?>.pdf");
                    formData.append("_token", "<?php echo e(csrf_token()); ?>");
                    formData.append("invoice_id", "<?php echo e($addedInvoice->invoice_id); ?>");
                    formData.append("invoice_amnt", "<?php echo e($addedInvoice->final_amount); ?>");
                    formData.append("phone_number", "<?php echo e($addedInvoice->client->user->phone ?? ''); ?>");
                    // Send the PDF to the backend
                    $.ajax({
                        url: "<?php echo e(route('send.invoice')); ?>",
                        type: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            if (response) {
                                Swal.fire({
                                    title: "Success!",
                                    text: "Message sent successfully!",
                                    icon: "success",
                                    confirmButtonText: "OK"
                                });

                            }
                            else {
                                Swal.fire({
                                    title: "Error!",
                                    text: "Error sending invoice!",
                                    icon: "error",
                                    confirmButtonText: "OK"
                                });

                            }
                            $(".invoice-btn-section").show();
                        },
                        error: function () {
                            Swal.fire({
                                title: "Error!",
                                text: "Something went wrong while processing the request.",
                                icon: "error",
                                confirmButtonText: "OK"
                            });
                            $(".invoice-btn-section").show();
                        }
                    });
                });
            });
        });       
    </script>
    <script>
        $(function () {
            $(document).on('change', '#paper_size', function () {
                const paperId = $('#paper_size').val();
                const invoiceId = "<?php echo e($addedInvoice->id); ?>";

                window.location.href = "<?php echo e(route('pdf', ['id' => 'INVOICE_ID_PLACEHOLDER'])); ?>".replace('INVOICE_ID_PLACEHOLDER', invoiceId) + "?paperId=" + paperId;
            });
        });
    </script>
</body>

</html><?php /**PATH /opt/lampp/htdocs/lara_commonbilling_new/resources/views/pdf/pdf.blade.php ENDPATH**/ ?>