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

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
    <link rel="icon" type="image/png" href="../assets/img/favicon.png">
    <title>
        Billing
    </title>
    <!-- Fonts and icons     -->
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet" />
    <!-- Nucleo Icons -->
    <link href="{{asset('assets/css/bootstrap.min.css')}}" rel="stylesheet" />
    <link href="{{asset('assets/css/style.css')}}" rel="stylesheet" />
    <link type="text/css" rel="stylesheet" href="{{asset('assets/fonts/font-awesome/css/font-awesome.min.css')}}">
    <link href="{{asset('assets/css/nucleo-icons.css')}}" rel="stylesheet" />
    <link href="{{asset('assets/css/nucleo-svg.css')}}" rel="stylesheet" />
    <!-- Font Awesome Icons -->
    <link href="{{asset('assets/css/nucleo-svg.css')}}" rel="stylesheet" />
    <!-- CSS Files -->
    <link id="pagestyle" href="{{asset('assets/css/soft-ui-dashboard.css?v=1')}}" rel="stylesheet" />
    <style>
        .invoice-btn-section .row {
            display: flex;
            flex-wrap: nowrap;
            align-items: center;
        }

        .invoice-btn-section .btn {
            white-space: nowrap;
            margin: 0 5px;
        }

        .invoice-btn-section .form-select {
            min-width: 200px;
        }

        @media (max-width: 768px) {
            .invoice-btn-section .row {
                flex-wrap: wrap;
            }

            .invoice-btn-section .col-md-auto,
            .invoice-btn-section .col-md-3 {
                width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>

<body>
    <div class="invoice-1 invoice-content">
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="invoice-inner clearfix">
                        <div class="invoice-info clearfix" id="invoice_wrapper">
                            <div class="invoice-headar">
                                <div class="row g-0">
                                    <div class="col-sm-6">
                                        <div class="invoice-logo">
                                            <!-- logo started -->
                                            <div class="logo">
                                                <img src="{{ getFileUrl($settings->logo ? $settings->logo : 'storage/logo/logo_invoice.png') }}"
                                                    alt="logo">
                                            </div>
                                            <!-- logo ended -->
                                        </div>
                                    </div>
                                    <div class="col-sm-6 invoice-id">
                                        <div class="info">
                                            <h1 class="color-white inv-header-1">Order's</h1>
                                            <p class="color-white mb-1">Order Number
                                                <span>{{$addedInvoice->quote_id ?? ''}}</span>
                                            </p>
                                            <p class="color-white mb-0">Order Date
                                                <span>{{$addedInvoice->quote_date ? \Carbon\Carbon::parse($addedInvoice->quote_date)->format('d-m-Y') : ''}}</span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="invoice-top">
                                <div class="row">
                                    <div class="col-sm-6">
                                        <div class="invoice-number mb-30">
                                            <h4 class="inv-title-1">Order To</h4>
                                            <h2 class="name">{{$addedInvoice->client->user->name ?? ''}}</h2>
                                            <p class="invo-addr-1">
                                                (+91) {{$addedInvoice->client->user->phone ?? ''}} <br />
                                            </p>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="invoice-number mb-30">
                                            <div class="invoice-number-inner">
                                                <h4 class="inv-title-1">Order From</h4>
                                                <h2 class="name">{{$settings->company_name ?? ''}}</h2>
                                                <p class="invo-addr-1">
                                                    {{$settings->address ?? ''}} <br />
                                                    {{$settings->email ?? ''}} <br />
                                                    (+91) {{$settings->phone ?? ''}}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div>
                                <div class="table-responsive">
                                    <table class="table mb-0 table-striped invoice-table">
                                        <thead class="bg-active">
                                            <tr class="tr">
                                                <th>No.</th>
                                                <th class="pl0 text-start">Item Description</th>
                                                <th class="text-center">Price</th>
                                                <th class="text-center">Quantity</th>
                                                <th class="text-end">Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($addedInvoice->ordersItem as $index => $data)
                                                <tr class="tr">
                                                    <td>
                                                        <div class="item-desc-1">
                                                            <span>{{ $index + 1 }}</span>
                                                        </div>
                                                    </td>
                                                    <td class="pl0">{{$settings->native_name_flag=='A'? ($data->product->native_name ?? $data->product_name ):($data->product_name ?? '') }}</td>
                                                    <td class="text-center">{{$data->price ?? ''}}</td>
                                                    <td class="text-center">{{$data->quantity ?? ''}}</td>
                                                    <td class="text-end">{{$data->total ?? ''}}</td>
                                                </tr>
                                            @endforeach

                                            <tr class="tr2">
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td class="text-center">SubTotal</td>
                                                <td class="text-end">₹{{number_format($addedInvoice->amount ?? 0, 2)}}
                                                </td>
                                            </tr>

                                            <tr class="tr2">
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td class="text-center">Discount</td>
                                                <td class="text-end">
                                                    @php
                                                        $totalDiscount = 0;
                                                        $total = $addedInvoice->amount;
                                                        if ($addedInvoice->discount_type == 1) {
                                                            $totalDiscount = $addedInvoice->discount;
                                                        } elseif ($addedInvoice->discount_type == 2) {
                                                            $discountAmount = ($total * $addedInvoice->discount)
                                                                / 100;
                                                            $totalDiscount = $discountAmount;
                                                        } else {
                                                            $totalDiscount = 0;
                                                        }                                            
                                                    @endphp
                                                    ₹ {{number_format($totalDiscount ?? 0, 2)}}</td>
                                            </tr>
                                            <tr class="tr2">
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td class="text-center f-w-600 active-color">Grand Total</td>
                                                <td class="f-w-600 text-end active-color">₹
                                                    {{number_format(floor($total - $totalDiscount) ?? 0, 2)}}
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="invoice-bottom">
                                <div class="row">
                                </div>
                            </div>

                            <div class="invoice-btn-section clearfix d-print-none">
                                <div class="row align-items-center gx-2 gy-2 mt-0">
                                    <div class="col-md-3">
                                        <select name="paper_size" id="paper_size" class="form-select">
                                            <option value="">Select Standard paper size</option>
                                            @foreach ($paper as $item)
                                                <option value="{{$item->id}}">{{$item->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-auto">
                                        <a href="javascript:window.print()" class="btn">
                                            <i class="fa fa-print"></i> Print Order
                                        </a>
                                    </div>
                                    <div class="col-md-auto">
                                        <a id="invoice_download_btn" class="btn">
                                            <i class="fa fa-download"></i> Download Order
                                        </a>
                                    </div>

                                    <div class="col-md-auto">
                                        <a href='{{route('orders-index')}}' id="cancel-btn" class="btn">
                                            <i class="fa fa-arrow-left"></i> Back
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="{{asset('assets/js/core/popper.min.js')}}"></script>
    <script src="{{asset('assets/js/core/bootstrap.min.js')}}"></script>
    <script src="{{asset('assets/js/plugins/smooth-scrollbar.min.js')}}"></script>

    <script src="{{asset('assets/js/jspdf.min.js')}}"></script>
    <script src="{{asset('assets/js/html2canvas.js')}}"></script>
    <script src="{{asset('assets/js/app.js')}}"></script>
    <script>
        $(function () {

            'use strict';

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $(document).on('click', '#invoice_download_btn', function () {
                $(".invoice-btn-section").addClass('d-none');

                // Get the invoice wrapper element
                const element = $("#invoice_wrapper")[0];
                const scale = 2; // Higher scale for better quality

                // Options for html2canvas
                const options = {
                    scale: scale,
                    logging: false,
                    useCORS: true,
                    allowTaint: true,
                    scrollX: 0,
                    scrollY: 0,
                    windowWidth: element.scrollWidth,
                    windowHeight: element.scrollHeight
                };

                html2canvas(element, options).then(function (canvas) {
                    // Calculate PDF dimensions
                    const imgWidth = 210; // A4 width in mm
                    const imgHeight = (canvas.height * imgWidth) / canvas.width;

                    // Create PDF
                    const pdf = new jsPDF('p', 'mm', 'a4');

                    // Add image to PDF
                    const imgData = canvas.toDataURL('image/jpeg', 1.0);
                    pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);

                    // Save the PDF
                    const pdfBlob = pdf.output('blob');
                    const formData = new FormData();
                    formData.append("pdf_file", pdfBlob, "invoice.pdf");

                    $.ajax({
                        url: '{{ route('invoice.save') }}',
                        method: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (response) {
                            console.log("File saved successfully on the server.");
                            pdf.save("{{$addedInvoice->quote_id}}.pdf");
                            $(".invoice-btn-section").removeClass('d-none');
                        },
                        error: function (error) {
                            console.log("Error saving the file:", error);
                            $(".invoice-btn-section").removeClass('d-none');
                        }
                    });
                });
            });
        });
    </script>
    <script>
        $(function () {
            $(document).on('change', '#paper_size', function () {
                const paperId = $('#paper_size').val();
                const invoiceId = "{{ $addedInvoice->id }}";

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

</html>