<div class="modal fade " id="paymentModal">
    <div class="modal-dialog">
        <form id="ajaxPaymentForm" class="form " role="form" enctype="multipart/form-data" method="post" action="#">
            <?php echo csrf_field(); ?>
            <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>
                                    <?php if(checkSettings('change-payment-date') == 'enable'): ?>
                                        <?php if(auth()->user()->hasPermissionTo('change-payment-date')): ?>
                                            <input class="form-control" value="<?php echo e(today()->format('Y-m-d')); ?>"
                                                type="date" id="created_at">
                                        <?php else: ?>
                                            <input class="form-control" value="<?php echo e(today()->format('Y-m-d')); ?>"
                                                type="date" disabled id="created_at">
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <input class="form-control" value="<?php echo e(today()->format('Y-m-d')); ?>"
                                            type="date" disabled id="created_at">
                                    <?php 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"
                                            <?php echo e(today()->format('F') == 'January' ? 'selected' : ''); ?>>January</option>
                                        <option value="February"
                                            <?php echo e(today()->format('F') == 'February' ? 'selected' : ''); ?>>February</option>
                                        <option value="March" <?php echo e(today()->format('F') == 'March' ? 'selected' : ''); ?>>
                                            March</option>
                                        <option value="April" <?php echo e(today()->format('F') == 'April' ? 'selected' : ''); ?>>
                                            April</option>
                                        <option value="May" <?php echo e(today()->format('F') == 'May' ? 'selected' : ''); ?>>May
                                        </option>
                                        <option value="June" <?php echo e(today()->format('F') == 'June' ? 'selected' : ''); ?>>
                                            June</option>
                                        <option value="July" <?php echo e(today()->format('F') == 'July' ? 'selected' : ''); ?>>
                                            July</option>
                                        <option value="August"
                                            <?php echo e(today()->format('F') == 'August' ? 'selected' : ''); ?>>
                                            August</option>
                                        <option value="September"
                                            <?php echo e(today()->format('F') == 'September' ? 'selected' : ''); ?>>September
                                        </option>
                                        <option value="October"
                                            <?php echo e(today()->format('F') == 'October' ? 'selected' : ''); ?>>October</option>
                                        <option value="November"
                                            <?php echo e(today()->format('F') == 'November' ? 'selected' : ''); ?>>November
                                        </option>
                                        <option value="December"
                                            <?php echo e(today()->format('F') == 'December' ? 'selected' : ''); ?>>December
                                        </option>
                                    </select>

                                </div>
                            </div>

                            <?php 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>
                            <?php endif; ?>

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

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

                                    <?php if(auth()->user()->hasrole('Admin')): ?>
                                        <select name="collected_by" class="form-control " id="paymentCollectedBy"
                                            required>
                                            <option value="">Select Employee</option>
                                            <?php $__currentLoopData = employees(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $employee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <?php if($employee->admin == null || $employee->admin->user_accounting_status == 'yes'): ?>
                                                    <option value="<?php echo e($employee->id); ?>"><?php echo e($employee->name); ?></option>
                                                <?php endif; ?>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </select>
                                    <?php else: ?>
                                        <?php if(auth()->user()->hasPermissionTo('change-collector')): ?>
                                            <select name="collected_by" class="form-control" id="paymentCollectedBy"
                                                required>
                                                <option value="">Select Employee</option>
                                                <?php $__empty_1 = true; $__currentLoopData = employees(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $employee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                                    <?php if($employee->admin == null || $employee->admin->user_accounting_status == 'yes'): ?>
                                                        <option value="<?php echo e($employee->id); ?>"
                                                            <?php echo e($employee->admin_user_id == auth()->user()->id ? 'selected' : ''); ?>>
                                                            <?php echo e($employee->name); ?></option>
                                                    <?php endif; ?>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                                <?php endif; ?>
                                            </select>
                                        <?php else: ?>
                                            <select name="collected_by" class="form-control" id="paymentCollectedBy"
                                                required disabled>
                                                <option value="">Select Employee</option>
                                                <?php $__empty_1 = true; $__currentLoopData = employees(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $employee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                                    <option value="<?php echo e($employee->id); ?>"
                                                        <?php echo e($employee->admin_user_id == auth()->user()->id ? 'selected' : ''); ?>>
                                                        <?php echo e($employee->name); ?></option>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                                <?php endif; ?>
                                            </select>
                                        <?php endif; ?>


                                    <?php 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>
                                        <?php if(config('app.only_monthly_bill_show') == true): ?>
                                            <?php $__currentLoopData = imcomeHead(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $head): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <?php if(in_array($head->id, [5])): ?>
                                                    <option value="<?php echo e($head->id); ?>"
                                                        <?php echo e($head->id == 5 ? 'selected' : ''); ?>><?php echo e($head->name); ?>

                                                    </option>
                                                    <option value="12">Other</option>
                                                <?php endif; ?>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php else: ?>
                                            <?php $__currentLoopData = imcomeHead(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $head): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <?php if(in_array($head->id, [1, 2, 3, 4, 5, 6, 11, 12])): ?>
                                                    <option value="<?php echo e($head->id); ?>"
                                                        <?php echo e($head->id == 5 ? 'selected' : ''); ?>><?php echo e($head->name); ?>

                                                    </option>
                                                <?php endif; ?>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                                        <?php endif; ?>
                                    </select>
                                </div>
                            </div>
                            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('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>
                            <?php else: ?>
                                <div class="col-md-6"></div>
                            <?php endif; ?>

                            <?php 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>
                                                <?php for($i = 1; $i <= 30; $i++): ?>
                                                    <option value="<?php echo e($i); ?>"><?php echo e($i); ?></option>
                                                <?php endfor; ?>
                                            </select>
                                        </div>

                                    </div>
                                </div>
                            <?php 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>

                            <?php endif; ?>

                            <div class="col-md-6">
                                <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>
                            <?php if(checkSettings('bank_account_deposit_from_payment') == 'enable'): ?>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="bank_account_id">
                                            Bank Account (Optional)
                                        </label>
                                        <select name="bank_account_id" id="bank_account_id" class="form-control">
                                            <option value="">Select Bank Account</option>
                                            <?php
                                                $bankAccounts = \App\Models\Banking::where('status', 1)->get();
                                            ?>
                                            <?php if($bankAccounts->count() > 0): ?>
                                                <?php $__currentLoopData = $bankAccounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bankAccount): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <option value="<?php echo e($bankAccount->id); ?>"><?php echo e($bankAccount->account_name); ?> -- <?php echo e($bankAccount->bank_name); ?></option>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            <?php endif; ?>
                                        </select>
                                        <small class="text-muted">Payment will be deposited to this account.</small>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <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" <?php if(checkSettings('auto-payment-sms-send') == 'enable'): ?> checked <?php 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" <?php if(checkSettings('auto-payment-print') == 'enable'): ?> checked <?php 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>
<?php 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>

<?php endif; ?>


<?php /**PATH /var/www/html/extranet/radius-circle/resources/views/paymenthistory/paymentModal.blade.php ENDPATH**/ ?>