<div class="modal fade " id="paymentModal">
    <div class="modal-dialog">
        <form id="ajaxPaymentForm" class="form " role="form" enctype="multipart/form-data" method="post" action="#">
            @csrf
            <div class="modal-content" style="padding:5px 15px 5px 15px;">
                <div class="modal-header">
                    <h4 class="text-center">Payment For  <span id="clientNameHead"></span></h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="text-center" id="modalAlert"></div>
                    <div class="row">

                        <input type="hidden" name="client_id" value="" id="cid">
                        <input type="hidden" name="monthsms" id="monthsms" value="">
                        <input type="hidden" name="billIds[]" id="billIds" value="">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Payment Date</label>
                                    @if (checkSettings('change-payment-date') == 'enable')
                                        @if (auth()->user()->hasPermissionTo('change-payment-date'))
                                            <input class="form-control" value="{{ today()->format('Y-m-d') }}"
                                                type="date" id="created_at">
                                        @else
                                            <input class="form-control" value="{{ today()->format('Y-m-d') }}"
                                                type="date" disabled id="created_at">
                                        @endif
                                    @else
                                        <input class="form-control" value="{{ today()->format('Y-m-d') }}"
                                            type="date" disabled id="created_at">
                                    @endif
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">

                                    <label>Payment Month </label>
                                    <select name="month" class="form-control" id="ajaxPaymentMonth">
                                        <option value="">Select Month</option>
                                        <option value="January"
                                            {{ today()->format('F') == 'January' ? 'selected' : '' }}>January</option>
                                        <option value="February"
                                            {{ today()->format('F') == 'February' ? 'selected' : '' }}>February</option>
                                        <option value="March" {{ today()->format('F') == 'March' ? 'selected' : '' }}>
                                            March</option>
                                        <option value="April" {{ today()->format('F') == 'April' ? 'selected' : '' }}>
                                            April</option>
                                        <option value="May" {{ today()->format('F') == 'May' ? 'selected' : '' }}>May
                                        </option>
                                        <option value="June" {{ today()->format('F') == 'June' ? 'selected' : '' }}>
                                            June</option>
                                        <option value="July" {{ today()->format('F') == 'July' ? 'selected' : '' }}>
                                            July</option>
                                        <option value="August"
                                            {{ today()->format('F') == 'August' ? 'selected' : '' }}>
                                            August</option>
                                        <option value="September"
                                            {{ today()->format('F') == 'September' ? 'selected' : '' }}>September
                                        </option>
                                        <option value="October"
                                            {{ today()->format('F') == 'October' ? 'selected' : '' }}>October</option>
                                        <option value="November"
                                            {{ today()->format('F') == 'November' ? 'selected' : '' }}>November
                                        </option>
                                        <option value="December"
                                            {{ today()->format('F') == 'December' ? 'selected' : '' }}>December
                                        </option>
                                    </select>

                                </div>
                            </div>

                            @if (checkSettings('due-history-in-payment') == 'enable')
                                <div class="col-md-12">
                                    <label for=""> Due Month</label>
                                    <table class="table table-bordered">
                                        <tbody id="due-history-in-payment">

                                        </tbody>
                                    </table>
                                </div>
                            @endif

                            <div class="col-md-12">
                                <div class="form-group">
                                    <label>Payment Description</label>
                                    @if (checkSettings('payment_month_show_in_remark') == 'enable')
                                        <textarea name="description" id="paymentDescription" class="form-control" placeholder="Enter Description...">{{ today()->format('F') }}</textarea>
                                    @else
                                        <textarea name="description" id="paymentDescription" class="form-control" placeholder="Enter Description...">Payment of month : {{ today()->format('F') }}. Bill Month : {{ today()->format('F') }}</textarea>
                                    @endif
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Collected By </label>

                                    @if (auth()->user()->hasrole('Admin'))
                                        <select name="collected_by" class="form-control " id="paymentCollectedBy"
                                            required>
                                            <option value="">Select Employee</option>
                                            @foreach (employees() as $employee)
                                                @if ($employee->admin == null || $employee->admin->user_accounting_status == 'yes')
                                                    <option value="{{ $employee->id }}">{{ $employee->name }}</option>
                                                @endif
                                            @endforeach
                                        </select>
                                    @else
                                        @if (auth()->user()->hasPermissionTo('change-collector'))
                                            <select name="collected_by" class="form-control" id="paymentCollectedBy"
                                                required>
                                                <option value="">Select Employee</option>
                                                @forelse (employees() as $employee)
                                                    @if ($employee->admin == null || $employee->admin->user_accounting_status == 'yes')
                                                        <option value="{{ $employee->id }}"
                                                            {{ $employee->admin_user_id == auth()->user()->id ? 'selected' : '' }}>
                                                            {{ $employee->name }}</option>
                                                    @endif
                                                @empty
                                                @endforelse
                                            </select>
                                        @else
                                            <select name="collected_by" class="form-control" id="paymentCollectedBy"
                                                required disabled>
                                                <option value="">Select Employee</option>
                                                @forelse (employees() as $employee)
                                                    <option value="{{ $employee->id }}"
                                                        {{ $employee->admin_user_id == auth()->user()->id ? 'selected' : '' }}>
                                                        {{ $employee->name }}</option>
                                                @empty
                                                @endforelse
                                            </select>
                                        @endif


                                    @endif
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Payment Type</label>
                                    <select name="payment_type" class="form-control" id="paymentType" required>
                                        <option value="">Select Type</option>
                                        @if (config('app.only_monthly_bill_show') == true)
                                            @foreach (imcomeHead() as $head)
                                                @if (in_array($head->id, [5]))
                                                    <option value="{{ $head->id }}"
                                                        {{ $head->id == 5 ? 'selected' : '' }}>{{ $head->name }}
                                                    </option>
                                                    <option value="12">Other</option>
                                                @endif
                                            @endforeach
                                        @else
                                            @foreach (imcomeHead() as $head)
                                                @if (in_array($head->id, [1, 2, 3, 4, 5, 6, 11, 12]))
                                                    <option value="{{ $head->id }}"
                                                        {{ $head->id == 5 ? 'selected' : '' }}>{{ $head->name }}
                                                    </option>
                                                @endif
                                            @endforeach

                                        @endif
                                    </select>
                                </div>
                            </div>
                            @can('payment-discount')
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Discount(optional)</label>
                                        <input class="form-control" min="0" placeholder="Discount(optional)"
                                            type="number" name="discount" id="paymentDiscount">
                                    </div>
                                </div>
                            @else
                                <div class="col-md-6"></div>
                            @endcan

                            @if (getBillingType() == 'day_to_day' &&  auth()->user()->can('day_by_day_payment'))

                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="checkAmount"><input type="checkbox" id="checkAmount"> Enable
                                            Amount</label>
                                        <input id="paymentAmount" min="0" class="form-control"
                                            style="display:none" type="number" name="amount" required="">

                                        <div class="day_to_day_enable">
                                            <select class="form-control" name="paymentDay" id="paymentDay">
                                                <option value="">Select Day</option>
                                                @for ($i = 1; $i <= 30; $i++)
                                                    <option value="{{ $i }}">{{ $i }}</option>
                                                @endfor
                                            </select>
                                        </div>

                                    </div>
                                </div>
                            @else
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Payment Amount</label>
                                        <input id="paymentAmount" min="0" class="form-control" type="number"
                                            name="amount" required="">
                                    </div>
                                </div>

                            @endif

                            <div class="col-md-12">
                                <div class="form-group">
                                    <label>Money Receipt ID</label>
                                    <input class="form-control" placeholder="Receipt ID" type="text"
                                        id="moneyReceiptNumber" name="money_receipt_number">
                                </div>
                            </div>

                            <div class="col-md-12 row">
                                <div class="form-group col-md-6 mt-2">
                                    <label><input type="checkbox" class="checkbox" name="sms" value=""
                                            id="sms" @if (checkSettings('auto-payment-sms-send') == 'enable') checked @endif><b> Send
                                            SMS Notification</b> </label>
                                </div>
                                <div class="form-group col-md-6 mt-2">
                                    <label><input type="checkbox" class="checkbox" name="print" value=""
                                            id="print" @if (checkSettings('auto-payment-print') == 'enable') checked @endif><b> Print
                                            Invoice</b> </label>
                                </div>
                            </div>


                        </div>

                    </div>


                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal"
                        id="ajaxPaymentModalClose">Close</button>
                    <button class="btn btn-primary buttonHide" type="submit" id="ajaxPaymentProcess">Submit</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </form>
    </div>
    <!-- /.modal-dialog -->
</div>
@if (checkSettings('webusb-printer') == 'enable')
    <script>
        // WebUSB Printer functionality
        class WebUSBPrinter {
            constructor() {
                this.device = null;
                this.encoder = new TextEncoder();
                this.decoder = new TextDecoder();
            }

            async connect() {
                try {
                    // Request USB device with printer interface
                    this.device = await navigator.usb.requestDevice({
                        filters: [
                            {
                                vendorId: 0x0483, // Common printer vendor ID, adjust as needed
                                productId: 0x5740  // Common printer product ID, adjust as needed
                            },
                            {
                                vendorId: 0x03f0, // HP printers
                            },
                            {
                                vendorId: 0x04b8, // Epson printers
                            },
                            {
                                vendorId: 0x04cc, // Canon printers
                            }
                        ]
                    });

                    await this.device.open();
                    await this.device.selectConfiguration(1);
                    await this.device.claimInterface(0);

                    console.log('WebUSB printer connected:', this.device.productName);
                    return true;
                } catch (error) {
                    console.error('Failed to connect to WebUSB printer:', error);
                    return false;
                }
            }

            async print(text) {
                if (!this.device) {
                    console.error('No printer connected');
                    return false;
                }

                try {
                    // Convert text to bytes
                    const data = this.encoder.encode(text);

                    // Send data to printer
                    await this.device.transferOut(1, data);

                    console.log('Print job sent successfully');
                    return true;
                } catch (error) {
                    console.error('Failed to print:', error);
                    return false;
                }
            }

            async disconnect() {
                if (this.device) {
                    await this.device.close();
                    this.device = null;
                    console.log('WebUSB printer disconnected');
                }
            }
        }

        // Initialize WebUSB printer
        const webUSBPrinter = new WebUSBPrinter();

        // Handle print checkbox functionality
        document.addEventListener('DOMContentLoaded', function() {
            const printCheckbox = document.getElementById('print');
            const paymentProcessBtn = document.getElementById('ajaxPaymentProcess');

            // Function to handle printer connection
            async function handlePrinterConnection() {
                // Check if WebUSB is supported
                if (!navigator.usb) {
                    alert('WebUSB is not supported in this browser. Please use Chrome or Edge.');
                    return false;
                }

                // Try to connect to printer
                const connected = await webUSBPrinter.connect();
                if (!connected) {
                    alert('Failed to connect to USB printer. Please ensure your printer is connected and try again.');
                    return false;
                }

                console.log('USB printer connected successfully!');
                return true;
            }

            // Check if checkbox is already checked on page load
            if (printCheckbox && printCheckbox.checked) {
                console.log('Print checkbox is already checked, WebUSB printer will be used on submit');
            }

            if (printCheckbox) {
                printCheckbox.addEventListener('change', async function() {
                    if (this.checked) {
                        await handlePrinterConnection();
                        if (!webUSBPrinter.device) {
                            this.checked = false;
                        }
                    } else {
                        // Disconnect printer when unchecked
                        await webUSBPrinter.disconnect();
                    }
                });
            }

            // Handle form submission with printing
            if (paymentProcessBtn) {
                paymentProcessBtn.addEventListener('click', async function(e) {
                    if (printCheckbox && printCheckbox.checked) {
                        // Check if printer is already connected
                        if (!webUSBPrinter.device) {
                            // Try to connect to printer if not already connected
                            const connected = await webUSBPrinter.connect();
                            if (!connected) {
                                alert('Failed to connect to USB printer. Please ensure your printer is connected and try again.');
                                e.preventDefault();
                                return;
                            }
                        }

                        // Generate receipt content
                        const receiptContent = generateReceiptContent();

                        // Print receipt
                        const printSuccess = await webUSBPrinter.print(receiptContent);

                        if (!printSuccess) {
                            alert('Failed to print receipt. Please check your printer connection.');
                            e.preventDefault();
                            return;
                        }

                        console.log('Receipt printed successfully via WebUSB');
                    }
                });
            }
        });

        // Function to generate receipt content
        function generateReceiptContent() {
            const clientName = document.getElementById('clientNameHead')?.textContent || 'Client';
            const paymentAmount = document.getElementById('paymentAmount')?.value || '0';
            const paymentDate = document.getElementById('created_at')?.value || new Date().toISOString().split('T')[0];
            const paymentType = document.getElementById('paymentType')?.selectedOptions[0]?.text || 'Payment';
            const receiptNumber = document.getElementById('moneyReceiptNumber')?.value || 'N/A';

            return `
        ==========================================
                    PAYMENT RECEIPT
        ==========================================
        Date: ${paymentDate}
        Receipt No: ${receiptNumber}
        Client: ${clientName}
        Payment Type: ${paymentType}
        Amount: $${paymentAmount}
        ==========================================
        Thank you for your payment!
        ==========================================
        `;
        }

        // Add WebUSB permission request button (optional)
        function addWebUSBButton() {
            const modalBody = document.querySelector('#paymentModal .modal-body');
            if (modalBody) {
                const usbButton = document.createElement('button');
                usbButton.type = 'button';
                usbButton.className = 'btn btn-info btn-sm mb-2';
                usbButton.textContent = 'Connect USB Printer';
                usbButton.onclick = async () => {
                    const connected = await webUSBPrinter.connect();
                    if (connected) {
                        alert('USB printer connected successfully!');
                        document.getElementById('print').checked = true;
                    }
                };

                modalBody.insertBefore(usbButton, modalBody.firstChild);
            }
        }

        // Initialize WebUSB button when modal is shown
        document.addEventListener('DOMContentLoaded', function() {
            const paymentModal = document.getElementById('paymentModal');
            if (paymentModal) {
                paymentModal.addEventListener('shown.bs.modal', function() {
                    addWebUSBButton();
                });
            }
        });
    </script>

@endif


