@extends('layouts.app')

@section('main')
    <style>
        .select2-selection--single .select2-selection__rendered {
            margin-top: -9px !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__clear {
            margin-top: -9px !important;
        }

        /* Fixed table header */
        #invoiceTable .table thead {
            position: sticky;
            top: 0;
            /* background-color: #cfe2ff; */
            /* table-primary background */
            z-index: 10;
        }

        #invoiceTable .table tbody {
            max-height: 350px;
            /* Adjust as needed to fit within 400px container */
            overflow-y: auto;
        }
    </style>
    <div class="container-fluid">
        <style>
            .main-sidebar,
            .main-header,
            .main-footer {
                display: none !important;
            }

            .content-wrapper {
                margin-left: 0 !important;
            }

            .container-fluid {
                padding-top: 100px;
                padding-bottom: 300px;
            }

            .top_card {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                z-index: 1050;
                background-color: white;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            }

            #payment_card {
                position: fixed;
                bottom: 0;
                left: 0;
                width: 100%;
                z-index: 1050;
                box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
                background-color: white;
            }

            .card-body {
                padding: 13px !important;
            }
        </style>

        <div class="row">
            <div class="col-lg-12">
                <div class="card top_card">
                    <div class="card-body">
                        <div class="row align-items-center">
                            {{-- <div class="col-md-2">
                                <h5 class="mb-0">Sales Invoice</h5>
                                <small class="text-muted">Invoice #INV-2024-001</small>
                            </div> --}}
                            {{-- <div class="col-md-2">Cashier: abay</div> --}}
                            {{-- <div class="col-md-3">
                                <input type="text" class="form-control" id="itemBarcodeSearch"
                                    placeholder="Search item / Barcode">
                            </div> --}}
                            <div class="col-md-1">
                                <a href="{{ route('home') }}" class="btn btn-primary">
                                    <i class="fas fa-angle-double-left"></i>
                                </a>
                            </div>

                            <div class="col-md-2 text-left">
                                <button class="btn btn-warning w-100" data-bs-toggle="modal"
                                    data-bs-target="#exchangeModal">
                                    +
                                    Exchange</button>
                            </div>


                            <div class="col-4">
                                <select class="form-select" id="customerSelect" name="customer"
                                    style="height:50px; font-size: 16px; min-width: 100%;">
                                </select>
                            </div>
                            <div class="col-3 d-flex align-items-center">
                                <button type="button" class="btn btn-primary" id="addCustomerBtn"
                                    style="height: 25px; font-size: 14px; padding: 0 8px;" data-bs-toggle="modal"
                                    data-bs-target="#customerModal">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                            <div class="col-2 text-right">
                                <button class="btn btn-outline-secondary" id="fullscreenBtn">
                                    <i class="fas fa-expand" id="fullscreenIcon"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- POS Pricing Information Banner -->
        @if($all_settings && $all_settings->pos_price_type && $all_settings->pos_price_value)
            <div class="row" style="margin-top: 70px;">
                <div class="col-12">
                    <div class="alert alert-info alert-dismissible fade show mb-3">
                        <i class="fas fa-cash-register mr-2"></i>
                        <strong>POS Pricing Active:</strong> 
                        {{ ucfirst($all_settings->pos_price_type) }} markup of 
                        @if($all_settings->pos_price_type === 'percentage')
                            {{ $all_settings->pos_price_value }}%
                        @else
                            {{ $all_settings->currency ?? 'BDT' }} {{ $all_settings->pos_price_value }}
                        @endif
                        applied to all products.
                        <a href="{{ route('settings.index') }}" class="btn btn-sm btn-outline-primary ml-2">
                            <i class="fas fa-cog"></i> Adjust Settings
                        </a>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                </div>
            </div>
        @endif

        <div class="row">
            <!-- Left Column: Invoice -->
            <div class="col-lg-8">


                <div class="table-responsive" id="invoiceTable" style="max-height:400px;overflow-y:auto;">
                    <table class="table table-striped align-middle">
                        <thead class="table-primary">
                            <tr>
                                <th>Product</th>
                                <th>Stock</th>
                                <th>Qty</th>
                                <th>Price</th>
                                <th>Subtotal</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="invoiceItems"></tbody>
                    </table>
                </div>

                <div class="card mb-4">
                    <div class="card-body bg-light">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="sendWhatsApp" disabled>
                            <label for="sendWhatsApp" class="form-check-label">Send Invoice via WhatsApp Web</label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Column: Products -->
            <div class="col-12 col-md-4">
                <div class="card h-100">
                    <div class="card-body d-flex flex-column" style="max-height:600px;overflow-y:auto;">
                        <div class="mb-3">


                            <div class="row g-2 mb-2">
                                <div class="col-6">
                                    <select class="form-select form-select-sm" id="brandSelect">
                                        <option value="">All Brands</option>
                                        @foreach ($brands as $brand)
                                            <option value="{{ $brand->id }}">{{ $brand->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-6">
                                    <select class="form-select form-select-sm" id="modelSelect" disabled>
                                        <option value="">All Models</option>
                                    </select>
                                </div>
                            </div>



                            <input type="hidden" id="selectedCustomerMobile">
                            <input type="text" class="form-control form-control-sm" placeholder="Search products..."
                                id="productSearch">
                        </div>

                        <div class="product-list flex-grow-1" id="productList"
                            style="overflow-y:auto;max-height:calc(100vh - 280px);">
                            <div class="alert alert-info alert-sm mb-2 p-2" style="font-size: 12px;">
                                <i class="fas fa-info-circle"></i> <strong>Tip:</strong> Single click to set custom price | Double click to add with default price
                            </div>
                            <div class="row row-cols-2 row-cols-sm-3 row-cols-md-4 g-2" id="productGrid">
                                    @foreach ($products as $product)
                                        @php
                                            // Calculate POS price based on settings
                                            $basePrice = $product->buy_price;
                                            $posPrice = $basePrice;
                                            
                                            if ($all_settings && $all_settings->pos_price_type && $all_settings->pos_price_value) {
                                                if ($all_settings->pos_price_type === 'percentage') {
                                                    $posPrice = $basePrice + ($basePrice * ($all_settings->pos_price_value / 100));
                                                } elseif ($all_settings->pos_price_type === 'fixed') {
                                                    $posPrice = $basePrice + $all_settings->pos_price_value;
                                                }
                                            }
                                        @endphp
                                        <div class="col">
                                            <div class="card product-card h-100 shadow-sm border-0" role="button"
                                                data-brand-id="{{ $product->brand_id ?? '' }}"
                                                data-model-id="{{ $product->mobile_model_id ?? '' }}"
                                                data-id="{{ $product->id }}" data-name="{{ $product->name }}"
                                                data-stock="{{ (int) $product->stock }}"
                                                data-price="{{ number_format($posPrice, 2, '.', '') }}"
                                                data-base-price="{{ number_format($basePrice, 2, '.', '') }}"
                                                data-image="{{ $product->image ?? asset('images/default-product.png') }}">
                                                <div class="card-body p-1 text-center">
                                                    <img src="{{ $product->image }}" alt="{{ $product->name }}"
                                                        class="img-fluid rounded"
                                                        style="width:55px;height:55px;object-fit:cover;"
                                                        onerror="this.onerror=null;this.src='{{ asset('images/default-product.png') }}'">
                                                    <div class="fw-bold text-truncate" style="font-size:0.8rem;">
                                                        {{ $product->name }}
                                                    </div>
                                                    <small class="text-muted d-block mb-1 stock-display"
                                                        style="font-size:0.7rem;"
                                                        data-current-stock="{{ $product->stock }}">Stock:
                                                        {{ $product->stock }}</small>
                                                    <div class="text-success fw-bold" style="font-size:0.75rem;">
                                                        {{ $all_settings->currency ?? 'BDT' }} {{ number_format($posPrice, 2) }}
                                                        @if($posPrice != $basePrice)
                                                            <small class="text-muted d-block" style="font-size:0.65rem;">
                                                                Base: {{ $all_settings->currency ?? 'BDT' }} {{ number_format($basePrice, 2) }}
                                                            </small>
                                                        @endif
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>

        <div class="card" style="margin-bottom: 0;" id="payment_card">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="row text-center">
                            <div class="col-md-3 p-0">
                                <small class="text-muted">TOTAL ITEMS</small>
                                <h5 class="text-info" id="totalItems">0</h5>
                            </div>
                            <div class="col-md-3 p-0">
                                <small class="text-muted">TOTAL AMOUNT</small>
                                <h5 class="text-primary" id="totalAmount">0.00</h5>
                            </div>
                            <div class="col-md-3 p-0">
                                <small class="text-muted">TOTAL DISCOUNT</small>
                                <h5 class="text-warning" id="totalDiscount">0.00</h5>
                            </div>
                            <div class="col-md-3 p-0">
                                <small class="text-muted">GRAND TOTAL</small>
                                <h5 class="text-success" id="grandTotal">0.00</h5>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-2" id="payDueContainer" style="display:none;">
                            <label for="payDue" class="form-label">Pay Due Amount</label>
                            <div class="input-group input-group-sm">
                                <input type="number" class="form-control" id="payDue" name="pay_due" min="0"
                                    step="0.01" placeholder="Enter amount to pay">
                                <button class="btn btn-success" type="button" id="payDueBtn"
                                    onclick="payCustomerDue()">Pay</button>
                            </div>
                        </div>
                        <form id="sellForm" action="{{ route('sell.store') }}" method="POST">
                            @csrf
                            <input type="hidden" name="customer_id" id="customerId">
                            <input type="hidden" name="items" id="itemsData">
                            <input type="hidden" name="exchanges" id="exchangesData">
                            <input type="hidden" name="payments" id="paymentsData">
                            <input type="hidden" name="payment_method" id="paymentMethod">
                            <input type="hidden" name="pay_due" id="payDueHidden">

                            <div class="row g-2">
                                <div class="col-4">
                                    <button type="button" onclick="validateCreditPayment()"
                                        class="btn btn-warning w-100">
                                        Credits
                                    </button>
                                </div>
                                <div class="col-4">
                                    <button type="button" onclick="setPaymentMethod('cash'); submitForm()"
                                        class="btn btn-success w-100">
                                        Cash ({{ $all_settings->currency ?? 'BDT' }} <span id="cashAmount">0.00</span>)
                                    </button>
                                </div>
                                <div class="col-4">
                                    <button type="button" class="btn btn-primary w-100" data-bs-toggle="modal"
                                        data-bs-target="#multiplePaymentModal">
                                        Multiple Payments
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Customer Modal -->
    <div class="modal fade" id="customerModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5>Add Customer</h5>
                    <button type="button" data-bs-dismiss="modal"
                        style="background:none;border:none;font-size:22px;font-weight:bold;color:#333;cursor:pointer;">X</button>
                </div>
                <div class="modal-body">
                    <form id="customerForm">@csrf
                        <div class="mb-3"><label>Name</label><input type="text" class="form-control"
                                name="customer_name" required></div>
                        <div class="mb-3"><label>Number</label><input type="text" class="form-control"
                                name="customer_number" id="customerNumber" required>
                            <small id="phoneExistsWarning" class="text-danger" style="display:none;">This phone number
                                already exists for customer: <span id="existingCustomerName"></span></small>
                        </div>
                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label>CPR/ID Number</label>
                                    <input type="text" class="form-control" name="customer_cpr" placeholder="Enter CPR or ID number">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label>CPR/ID Photo</label>
                                    <div class="custom-file-upload">
                                        <input type="file" class="form-control-file" name="cpr_photo" id="cprPhotoInput" 
                                               accept="image/*" style="display: none;" onchange="previewCprPhoto(event)">
                                        <button type="button" class="btn btn-outline-primary btn-sm w-100" onclick="document.getElementById('cprPhotoInput').click()">
                                            <i class="fas fa-camera mr-2"></i>
                                            Upload ID Photo
                                        </button>
                                    </div>
                                    <div id="cprPhotoPreview" class="mt-2" style="display: none;">
                                        <img id="cprPhotoImg" src="" alt="CPR Photo Preview" 
                                             class="img-thumbnail" style="width: 100%; max-height: 80px; object-fit: cover;">
                                        <button type="button" class="btn btn-danger btn-xs mt-1 w-100" onclick="removeCprPhoto()">
                                            <i class="fas fa-trash mr-1"></i>Remove Photo
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3"><label>Address</label>
                            <textarea class="form-control" name="address" rows="2" placeholder="Enter customer address"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button class="btn btn-success" onclick="saveCustomer()">Save</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Exchange Modal -->
    <div class="modal fade" id="exchangeModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5>Add Exchange Product</h5>
                    <button type="button" data-bs-dismiss="modal"
                        style="background:none;border:none;font-size:22px;font-weight:bold;color:#333;cursor:pointer;">X</button>
                </div>
                <div class="modal-body">
                    <form id="exchangeForm">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Brand</label>
                                <select class="form-control" id="exchangeBrandSelect">
                                    <option value="">Select Brand</option>
                                    @foreach ($brands as $brand)
                                        <option value="{{ $brand->id }}">{{ $brand->name }}</option>
                                    @endforeach
                                </select>
                                <input type="text" class="form-control mt-2" id="exchangeBrandInput"
                                    placeholder="Or type brand name">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>Model</label>
                                <select class="form-control" id="exchangeModelSelect" disabled>
                                    <option value="">Select Model</option>
                                </select>
                                <input type="text" class="form-control mt-2" id="exchangeModelInput"
                                    placeholder="Or type model name">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>Price</label>
                                <input type="number" class="form-control" id="exchangePrice" step="0.01" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>IMEI</label>
                                <input type="text" class="form-control" id="exchangeImei" required>
                            </div>
                        </div>
                        <button type="button" class="btn btn-primary" onclick="addExchange()">Add Exchange</button>
                    </form>
                    <hr>
                    <h6>Exchange Items</h6>
                    <ul id="exchangeList" class="list-group"></ul>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Custom Price Modal -->
    <div class="modal fade" id="customPriceModal" tabindex="-1" aria-labelledby="customPriceModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="customPriceModalLabel">Set Custom Price</h5>
                    <button type="button" class="btn-close" onclick="closeCustomPriceModal()" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Product: <strong id="customPriceProductName"></strong></label>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">POS Price: <strong id="customPriceDefaultPrice"></strong></label>
                        <div id="customPriceBasePriceDiv" style="display: none;">
                            <small class="text-muted">Base Price: <span id="customPriceBasePrice"></span></small>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="customPriceInput" class="form-label">Custom Price</label>
                        <div class="input-group">
                            <span class="input-group-text" id="customPriceCurrency">{{ $all_settings->currency ?? 'BDT' }}</span>
                            <input type="number" class="form-control" id="customPriceInput" step="0.01" min="0" placeholder="Enter custom price">
                            <button class="btn btn-outline-secondary" type="button" onclick="useDefaultPrice()">
                                <i class="fas fa-undo"></i> Default
                            </button>
                        </div>
                        @if($all_settings && $all_settings->pos_price_type && $all_settings->pos_price_value)
                            <small class="text-info">
                                <i class="fas fa-info-circle"></i> 
                                POS pricing: {{ ucfirst($all_settings->pos_price_type) }} 
                                @if($all_settings->pos_price_type === 'percentage')
                                    {{ $all_settings->pos_price_value }}% markup
                                @else
                                    {{ $all_settings->currency ?? 'BDT' }} {{ $all_settings->pos_price_value }} markup
                                @endif
                            </small>
                        @endif
                    </div>
                    <div class="mb-3">
                        <label for="customQuantityInput" class="form-label">Quantity</label>
                        <input type="number" class="form-control" id="customQuantityInput" min="1" value="1">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeCustomPriceModal()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="addProductWithCustomPrice()">Add to Cart</button>
                </div>
            </div>
        </div>
    </div>

    <style>
        .product-list {
            scrollbar-width: thin;
        }

        .product-card {
            transition: 0.2s ease-in-out;
        }

        .product-card:hover {
            transform: scale(1.05);
            border: 1px solid #0d6efd;
            cursor: pointer;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        /* Custom Price Modal Styling */
        #customPriceModal .modal-body {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        }

        #customPriceModal .input-group-text {
            background-color: #28a745;
            color: white;
            font-weight: bold;
        }

        #customPriceInput:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
        }

        /* Product card hints */
        .product-card::after {
            content: "Single click: Custom Price | Double click: Default Price";
            position: absolute;
            bottom: -25px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 10px;
            white-space: nowrap;
            opacity: 0;
            transition: opacity 0.3s;
            pointer-events: none;
            z-index: 10;
        }

        .product-card:hover::after {
            opacity: 1;
        }

        .product-card .card-body {
            padding: 0.5rem !important;
        }

        .pos-fullscreen {
            position: fixed !important;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            z-index: 1040;
            background: white;
            overflow-y: auto;
            margin: 0;
            padding: 15px;
        }

        /* fullscreen mode */
        .modal {
            z-index: 1050 !important;
        }

        .modal-backdrop {
            z-index: 1045 !important;
        }

        body.fullscreen-mode .sidebar,
        body.fullscreen-mode .main-sidebar,
        body.fullscreen-mode .navbar-nav,
        body.fullscreen-mode .main-header,
        body.fullscreen-mode .main-footer {
            display: none !important;
        }

        @media (max-width:768px) {
            .pos-fullscreen .col-lg-8 {
                width: 100% !important
            }

            .pos-fullscreen .col-md-4 {
                width: 100% !important;
                margin-top: 20px
            }
        }

        #fullscreenBtn {
            transition: all .3s
        }

        #fullscreenBtn:hover {
            background-color: #0d6efd;
            color: #fff;
            border-color: #0d6efd
        }

        /* Additional styles for Select2 clear (x) button */
        .select2-container--default .select2-selection--single .select2-selection__clear {
            margin-top: -9px !important;
            color: #dc3545 !important;
            /* Bootstrap danger color */
            font-size: 18px !important;
            cursor: pointer !important;
            opacity: 0.8 !important;
            transition: opacity 0.3s ease;
        }

        .select2-container--default .select2-selection--single .select2-selection__clear:hover {
            opacity: 1 !important;
            color: #bd2130 !important;
            /* Darker danger color on hover */
        }

        /* Print styles */
        @media print {
            body * {
                visibility: hidden;
            }

            /* #printArea,
                                                                                                #printArea * {
                                                                                                    visibility: visible;
                                                                                                }

                                                                                                #printArea {
                                                                                                    position: absolute;
                                                                                                    left: 0;
                                                                                                    top: 0;
                                                                                                    width: 100%;
                                                                                                } */
        }
    </style>

    <!--  Toastr CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <!-- jQuery (AdminLTE already includes it, but adding for safety) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <!-- Toastr JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <!-- Enhanced Notification System with Sound is loaded in app.blade.php -->
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        // Configure Toastr options
        toastr.options = {
            "closeButton": true,
            "debug": false,
            "newestOnTop": true,
            "progressBar": true,
            "positionClass": "toast-top-right",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "4000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        };

        // Initialize Enhanced Notification System
        let notificationSystem;
        $(document).ready(function() {
            notificationSystem = new NotificationSystem();
        });

        // Initialize customers data early (global access)
        window.customers = @json($customers);
        console.log('DEBUG: Initialized window.customers:', window.customers);


        // Submit form function
        function submitForm() {
            const customerSelect = document.getElementById('customerSelect');
            let customerId = customerSelect.value || '';
            const customerMobile = customerSelect.options[customerSelect.selectedIndex]?.dataset
                ?.mobile || '';

            // If walk-in selected, set customer_id to null
            if (customerId === 'walk_in') {
                customerId = null;
            }

            document.getElementById('customerId').value = customerId;

            console.log('Customer Data:', {
                customerId,
                customerMobile
            });

            const rows = document.querySelectorAll('#invoiceItems tr');
            const items = Array.from(rows).filter(row => !row.dataset.id.startsWith('exchange_')).map(row => {
                // Use base price from data attribute for transaction, not the displayed price
                const basePrice = parseFloat(row.dataset.basePrice) || 0;
                
                // Ensure price is always a valid number
                if (isNaN(basePrice) || basePrice <= 0) {
                    console.error('Invalid base price detected for product:', row.dataset.id);
                    basePrice = 1; // Fallback to a minimum price
                }
                
                const item = {
                    product_id: row.dataset.id,
                    name: row.querySelector('td:first-child').innerText.trim(),
                    stock: row.querySelector('td:nth-child(2)').innerText.trim(),
                    sold_quantity: Number(row.querySelector('.quantity-value').innerText.trim() || 0),
                    price: basePrice,  // Use base price for actual transaction
                    subtotal: parseFloat(row.querySelector('.subtotal').innerText.replace(/{{ $all_settings->currency ?? 'BDT' }}|,/g, '').trim()) || 0
                };
                
                // Debug log each item
                console.log('Cart item (using base price for transaction):', item);
                return item;
            });

            // Debug output - check each item structure
            console.log('Final items data being sent:', items);
            items.forEach((item, index) => {
                console.log(`Item ${index}:`, item);
                console.log(`Item ${index} keys:`, Object.keys(item));
            });
            console.log('Exchanges data:', exchanges);
            console.log('Payments data:', payments);
            
            document.getElementById('itemsData').value = JSON.stringify(items);
            document.getElementById('exchangesData').value = JSON.stringify(exchanges);
            document.getElementById('paymentsData').value = JSON.stringify(payments);

            // Clear payDueHidden to prevent automatic payment unless user manually entered amount
            // Only keep the value if user manually clicked Pay Due button
            const payDueHidden = document.getElementById('payDueHidden');
            if (payDueHidden && !payDueHidden.dataset.manuallySet) {
                payDueHidden.value = '';
            }

            // AJAX form submission
            const form = document.getElementById('sellForm');
            const url = form.action;
            const formData = new FormData(form);

            fetch(url, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': form.querySelector('input[name="_token"]').value,
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                    body: formData,
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => {
                            throw new Error(errData.message || 'Failed to submit sale');
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Sale submission response:', data);
                    if (data.sale_id) {
                        // Store sale data for modal use
                        window.currentSaleData = data;
                        console.log('Sale data stored:', window.currentSaleData);
                        
                        // Show sale completion modal instead of immediate actions
                        showSaleCompletionModal(data);
                        // This will be handled by the modal buttons
                    } else {
                        console.error('No sale_id in response:', data);
                        if (notificationSystem) {
                            notificationSystem.showError('Sale completed but no invoice available.');
                        } else {
                            toastr.error('Sale completed but no invoice available.');
                        }
                    }
                })
                .catch(error => {
                    if (notificationSystem) {
                        notificationSystem.showError(error.message);
                    } else {
                        toastr.error(error.message);
                    }
                    console.error('Error submitting sale:', error);
                });
        }

        // Show sale completion modal
        function showSaleCompletionModal(saleData) {
            console.log('Showing sale completion modal with data:', saleData);
            
            // Populate modal with sale details
            const saleIdEl = document.getElementById('completedSaleId');
            const customerNameEl = document.getElementById('completedCustomerName');
            const amountEl = document.getElementById('completedAmount');
            
            if (saleIdEl) saleIdEl.textContent = saleData.sale_id;
            
            // Get customer info from current selection
            const customerSelect = document.getElementById('customerSelect');
            const customerName = customerSelect.options[customerSelect.selectedIndex]?.text || 'Walk-in Customer';
            if (customerNameEl) customerNameEl.textContent = customerName;
            
            // Calculate total from current cart
            const grandTotalEl = document.getElementById('grandTotal');
            const grandTotal = grandTotalEl ? grandTotalEl.textContent : 'N/A';
            if (amountEl) amountEl.textContent = grandTotal;
            
            console.log('Modal data populated - Sale ID:', saleData.sale_id, 'Customer:', customerName, 'Amount:', grandTotal);
            
            // Show the modal
            try {
                const modalElement = document.getElementById('saleCompletionModal');
                if (modalElement) {
                    const modal = new bootstrap.Modal(modalElement);
                    modal.show();
                    console.log('Modal should be visible now');
                    
                    // Show enhanced notification with sound for sale completion
                    if (notificationSystem) {
                        console.log('Calling saleComplete notification...');
                        notificationSystem.saleComplete(
                            'Sale Completed Successfully!',
                            `Invoice #${saleData.sale_id} - Customer: ${customerName} - Amount: ${grandTotal}`
                        );
                    }
                } else {
                    console.error('Modal element not found!');
                    if (notificationSystem) {
                        notificationSystem.showError('Sale completion modal not found!');
                    } else {
                        toastr.error('Sale completion modal not found!');
                    }
                }
            } catch (error) {
                console.error('Error showing modal:', error);
                if (notificationSystem) {
                    notificationSystem.showError('Error showing completion modal: ' + error.message);
                } else {
                    toastr.error('Error showing completion modal: ' + error.message);
                }
            }
        }

        // Handle print invoice button
        function printInvoice() {
            window.modalActionTaken = true; // Set flag to prevent auto-clear
            
            if (!window.currentSaleData || !window.currentSaleData.sale_id) {
                toastr.error('No sale data available for printing!');
                return;
            }
            
            const saleId = window.currentSaleData.sale_id;
            const printUrl = `/sales/${saleId}/table-invoice`;
            
            console.log('Opening invoice for printing:', printUrl);
            window.open(printUrl, '_blank');
            
            // Clear the form after printing
            clearPosForm();
            
            // Hide the modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('saleCompletionModal'));
            if (modal) {
                modal.hide();
            }
            
            if (notificationSystem) {
                notificationSystem.showSuccess('Invoice opened for printing!');
            } else {
                toastr.success('Invoice opened for printing!');
            }
        }

        // Build sale data from current cart for WhatsApp
        function buildSaleDataFromCart(saleId, customerName, customerPhone) {
            const invoiceItems = document.getElementById('invoiceItems');
            const items = [];
            
            // Extract items from current cart
            invoiceItems.querySelectorAll('.invoice-item').forEach(row => {
                const productName = row.querySelector('.product-name')?.textContent || 'Unknown Product';
                const quantity = row.querySelector('.quantity')?.textContent || '1';
                const unitPrice = row.querySelector('.unit-price')?.textContent || '0';
                const totalPrice = row.querySelector('.total-price')?.textContent || '0';
                
                items.push({
                    product_name: productName,
                    quantity: quantity,
                    unit_price: unitPrice,
                    total_price: totalPrice
                });
            });
            
            // Get totals from current calculation
            const grandTotalEl = document.getElementById('grandTotal');
            const totalAmount = grandTotalEl ? grandTotalEl.textContent.replace(/[^\d.]/g, '') : '0';
            
            return {
                id: saleId,
                customer: {
                    name: customerName,
                    phone: customerPhone
                },
                items: items,
                total_amount: totalAmount,
                net_amount: totalAmount,
                payment_method: 'cash', // Default
                payment_status: 'paid', // Default for completed sales
                created_at: new Date().toISOString()
            };
        }

        // Handle send WhatsApp button
        function sendWhatsAppNotification() {
            console.log('DEBUG: window.customers exists?', typeof window.customers);
            console.log('DEBUG: window.customers value:', window.customers);
            
            window.modalActionTaken = true; // Set flag to prevent auto-clear
            
            if (!window.currentSaleData || !window.currentSaleData.sale_id) {
                toastr.error('No sale data available for WhatsApp!');
                return;
            }
            
            const saleId = window.currentSaleData.sale_id;
            console.log('Sending WhatsApp for sale ID:', saleId);
            
            // Get current customer and cart data
            const customerSelect = document.getElementById('customerSelect');
            const customerOption = customerSelect.options[customerSelect.selectedIndex];
            const customerName = customerOption?.text || 'Walk-in Customer';
            const customerId = customerSelect.value;
            
            // Get customer phone from the customers array
            let customerPhone = null;
            if (customerId !== 'walk_in') {
                const customer = window.customers.find(c => c.id == customerId);
                customerPhone = customer ? customer.phone : null;
                console.log('Found customer in global array:', customer);
            }
            
            console.log('Customer data:', { name: customerName, phone: customerPhone, id: customerId });
            
            // If no phone number available, show error
            if (!customerPhone || customerPhone === '00000000' || customerPhone.trim().length <= 5) {
                console.error('WhatsApp failed - no valid phone number. Phone:', customerPhone);
                toastr.warning('Customer mobile number not available for WhatsApp.');
                return;
            }
            
            // Show loading state
            const whatsappBtn = document.getElementById('sendWhatsAppBtn');
            const originalText = whatsappBtn.innerHTML;
            whatsappBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
            whatsappBtn.disabled = true;
            
            // Debug: Log the phone number being sent
            console.log('📱 Sending WhatsApp with phone:', customerPhone);
            console.log('📱 Phone length:', customerPhone.length);
            console.log('📱 Sale ID:', saleId);
            
            // Also format phone for comparison
            const frontendFormattedPhone = formatPhoneForWhatsApp(customerPhone);
            console.log('📱 Frontend formatted phone:', frontendFormattedPhone);
            
            // Use the same API endpoint as Sales Management Dashboard
            fetch('{{ route('whatsapp.send.invoice') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({
                    type: 'invoice',
                    id: saleId,
                    phone: customerPhone,
                    get_url_only: true
                })
            })
            .then(response => {
                console.log('📱 Raw Response Status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('📱 WhatsApp API Response:', data);
                console.log('📱 Backend formatted phone:', data.phone);
                console.log('📱 WhatsApp URL:', data.whatsapp_url);
                if (data.success && data.whatsapp_url) {
                    // Open WhatsApp in new tab/window
                    window.open(data.whatsapp_url, '_blank');
                    toastr.success('WhatsApp opened successfully! Please send the message from WhatsApp.');
                    
                    // Clear the form after WhatsApp
                    clearPosForm();
                    
                    // Hide the modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('saleCompletionModal'));
                    if (modal) {
                        modal.hide();
                    }
                } else {
                    console.error('❌ WhatsApp send failed:', data);
                    toastr.error(data.message || 'Failed to generate WhatsApp URL');
                }
            })
            .catch(error => {
                console.error('WhatsApp URL error:', error);
                toastr.error('An error occurred while generating the WhatsApp URL');
            })
            .finally(() => {
                // Restore button state
                whatsappBtn.innerHTML = originalText;
                whatsappBtn.disabled = false;
            });
            
            // Construct professional invoice message
            let message = `🧾 Invoice #${saleData.id}\n\n`;
            message += `👤 Customer: ${saleData.customer.name}\n`;
            message += `📞 Phone: ${saleData.customer.phone}\n`;
            message += `📅 Date: ${new Date(saleData.created_at).toLocaleDateString()}\n\n`;
            message += `📦 Items:\n`;
            
            // Add items from current cart
            if (saleData.items && saleData.items.length > 0) {
                saleData.items.forEach(item => {
                    message += `• ${item.product_name} x${item.quantity} @ ${currency} ${item.unit_price} = ${currency} ${item.total_price}\n`;
                });
            } else {
                message += `• No items found\n`;
            }
            
            message += `\n💰 Total Amount: ${currency} ${saleData.total_amount}\n`;
            
            // Get payment details from current sale form
            const paymentMethod = document.getElementById('paymentMethod')?.value || 'cash';
            const grandTotalEl = document.getElementById('grandTotal');
            const grandTotal = grandTotalEl ? parseFloat(grandTotalEl.textContent.replace(/[^\d.]/g, '')) : 0;
            
            // Debug payment method detection
            console.log('DEBUG - Payment method detected:', paymentMethod);
            console.log('DEBUG - Payment method element:', document.getElementById('paymentMethod'));
            console.log('DEBUG - Grand total:', grandTotal);
            
            // Check if there's due payment being made
            const payDueHidden = document.getElementById('payDueHidden');
            const payDueAmount = payDueHidden && payDueHidden.value ? parseFloat(payDueHidden.value) : 0;
            
            console.log('DEBUG - Pay Due Detection:');
            console.log('  payDueHidden element:', payDueHidden);
            console.log('  payDueHidden value:', payDueHidden ? payDueHidden.value : 'null');
            console.log('  payDueAmount parsed:', payDueAmount);
            
            // Calculate paid and due amounts for this sale
            const totalSaleAmount = grandTotal;
            let paidAmount = totalSaleAmount; // Default for cash
            let dueAmount = 0;
            
            if (paymentMethod === 'credit') {
                paidAmount = 0;
                dueAmount = totalSaleAmount;
            } else if (paymentMethod === 'partial') {
                // For partial payments, check if custom paid amount is set
                const customPaidInput = document.getElementById('customPaidAmount');
                if (customPaidInput && customPaidInput.value) {
                    paidAmount = parseFloat(customPaidInput.value);
                    dueAmount = totalSaleAmount - paidAmount;
                }
            }
            
            message += `💳 Payment Method: ${paymentMethod.charAt(0).toUpperCase() + paymentMethod.slice(1)}\n`;
            
            // For credit sales, show unpaid amount instead of paid amount
            if (paymentMethod === 'credit') {
                message += `⚠️ Unpaid Amount: ${currency} ${dueAmount.toFixed(2)}\n`;
            } else {
                message += `💵 Paid Amount: ${currency} ${paidAmount.toFixed(2)}\n`;
                if (dueAmount > 0) {
                    message += `⚠️ Due Amount: ${currency} ${dueAmount.toFixed(2)}\n`;
                }
            }
            
            // Add due payment info if customer paid towards previous due
            if (payDueAmount > 0) {
                message += `✅ Previous Due Paid: ${currency} ${payDueAmount.toFixed(2)}\n`;
            }
            
            message += `📊 Payment Status: ${dueAmount > 0 ? 'Partial' : 'Paid'}\n\n`;
            
            // Add customer total due information if available
            if (customerId !== 'walk_in') {
                // Fetch fresh customer due data from server instead of using stale window.customers data
                fetch(`/pos/customer-due?customer_id=${customerId}`)
                    .then(response => response.json())
                    .then(freshData => {
                        const currentDue = parseFloat(freshData.due) || 0;
                        
                        // The fresh data from server already includes the current sale
                        // So we don't need to add dueAmount again for the total outstanding
                        let finalOutstanding;
                        if (payDueAmount > 0) {
                            // Only subtract if payment was made towards previous due
                            finalOutstanding = currentDue - payDueAmount;
                        } else {
                            // For new customers or no due payment, use the fresh due as-is
                            finalOutstanding = currentDue;
                        }
                        
                        console.log('🔍 FRESH Customer Due Calculation:');
                        console.log('  💳 Payment Method:', paymentMethod);
                        console.log('  💰 Fresh customer due from server: BDT', currentDue, '(includes current sale)');
                        console.log('  📊 Current sale due amount: BDT', dueAmount, '(already included in server data)');
                        console.log('  💸 Payment towards old due: BDT', payDueAmount);
                        console.log('  📋 FINAL OUTSTANDING: BDT', finalOutstanding, '= fresh due - payments');
                        console.log('  📝 Original message length:', message.length);
                        
                        // Rebuild the customer outstanding part of the message
                        const messageLines = message.split('\n');
                        const newMessageLines = [];
                        let foundOutstandingLine = false;
                        
                        for (let line of messageLines) {
                            if (line.includes('📋 Customer Total Outstanding:')) {
                                foundOutstandingLine = true;
                                if (finalOutstanding > 0) {
                                    newMessageLines.push(`📋 Customer Total Outstanding: ${currency} ${finalOutstanding.toFixed(2)}`);
                                }
                                // Skip the old outstanding line
                            } else {
                                newMessageLines.push(line);
                            }
                        }
                        
                        // If we didn't find an outstanding line and there is outstanding amount, add it
                        if (!foundOutstandingLine && finalOutstanding > 0) {
                            // Insert before the "Thank you" line
                            const thankYouIndex = newMessageLines.findIndex(line => line.includes('🙏 Thank you'));
                            if (thankYouIndex > 0) {
                                newMessageLines.splice(thankYouIndex, 0, `📋 Customer Total Outstanding: ${currency} ${finalOutstanding.toFixed(2)}`, '');
                            } else {
                                newMessageLines.push(`📋 Customer Total Outstanding: ${currency} ${finalOutstanding.toFixed(2)}`, '');
                            }
                        }
                        
                        message = newMessageLines.join('\n');
                        console.log('  📝 Updated message length:', message.length);
                        console.log('  ✅ Message updated with fresh data');
                        
                        // Add the ending parts if not already there
                        if (!message.includes('🙏 Thank you for your business!')) {
                            message += `\n🙏 Thank you for your business!\n\n`;
                            message += `🔗 View full invoice: ${window.location.origin}/sales/${saleId}/table-invoice`;
                        }
                        
                        // Send WhatsApp after getting fresh data
                        const formattedPhone = formatPhoneForWhatsApp(customerPhone);
                        const whatsappUrl = `https://api.whatsapp.com/send/?phone=${formattedPhone}&text=${encodeURIComponent(message)}`;
                        
                        console.log('📱 Opening WhatsApp with FRESH data:', finalOutstanding);
                        console.log('📱 Formatted phone:', formattedPhone);
                        window.open(whatsappUrl, '_blank');
                        
                        // Clear the form after sending WhatsApp
                        clearPosForm();
                        
                        // Hide the modal
                        const modal = bootstrap.Modal.getInstance(document.getElementById('saleCompletionModal'));
                        if (modal) {
                            modal.hide();
                        }
                        
                        if (notificationSystem) {
                            notificationSystem.showSuccess('WhatsApp message opened successfully!');
                        } else {
                            toastr.success('WhatsApp message opened successfully!');
                        }
                    })
                    .catch(error => {
                        console.error('❌ Error fetching fresh customer due:', error);
                        console.log('🔄 Using fallback calculation with stale data...');
                        
                        // Fallback: Send WhatsApp with original message (may have wrong amount)
                        message += `🙏 Thank you for your business!\n\n`;
                        message += `🔗 View full invoice: ${window.location.origin}/sales/${saleId}/table-invoice`;
                        
                        const formattedPhone = formatPhoneForWhatsApp(customerPhone);
                        const whatsappUrl = `https://api.whatsapp.com/send/?phone=${formattedPhone}&text=${encodeURIComponent(message)}`;
                        
                        console.log('Opening WhatsApp with fallback data (may be incorrect)');
                        console.log('📱 Fallback formatted phone:', formattedPhone);
                        window.open(whatsappUrl, '_blank');
                        
                        clearPosForm();
                        const modal = bootstrap.Modal.getInstance(document.getElementById('saleCompletionModal'));
                        if (modal) {
                            modal.hide();
                        }
                        
                        if (notificationSystem) {
                            notificationSystem.showError('Customer due amount may be incorrect in WhatsApp message');
                        } else {
                            toastr.warning('Customer due amount may be incorrect in WhatsApp message');
                        }
                    });
                return; // Exit early since we're handling WhatsApp sending in the fetch callback
            }
            
            // For walk-in customers, send WhatsApp immediately
            message += `🙏 Thank you for your business!\n\n`;
            message += `🔗 View full invoice: ${window.location.origin}/sales/${saleId}/table-invoice`;

            // Format phone number with country code and open WhatsApp
            let walkinFormattedPhone = formatPhoneForWhatsApp(customerPhone);
            const whatsappUrl = `https://api.whatsapp.com/send/?phone=${walkinFormattedPhone}&text=${encodeURIComponent(message)}`;
            
            console.log('Opening WhatsApp with URL:', whatsappUrl);
            console.log('📱 Formatted phone:', walkinFormattedPhone);
            window.open(whatsappUrl, '_blank');
            
            // Clear the form after sending WhatsApp
            clearPosForm();
            
            // Hide the modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('saleCompletionModal'));
            if (modal) {
                modal.hide();
            }
            
            if (notificationSystem) {
                notificationSystem.showSuccess('WhatsApp message opened successfully!');
            } else {
                toastr.success('WhatsApp message opened successfully!');
            }
        }

        // Clear POS form after successful sale
        function clearPosForm() {
            // Clear invoice items
            document.getElementById('invoiceItems').innerHTML = '';
            // Clear customer select
            $('#customerSelect').val('walk_in').trigger('change');
            // Clear exchanges
            exchanges = [];
            updateExchangeList();
            // Reset pay due
            document.getElementById('payDue').value = '';
            const payDueHidden = document.getElementById('payDueHidden');
            if (payDueHidden) {
                payDueHidden.value = '';
                delete payDueHidden.dataset.manuallySet;
            }
            document.getElementById('payDueContainer').style.display = 'none';
            // Update summary
            updateSummary();
            // Reset stock displays
            document.querySelectorAll('.stock-display').forEach(display => {
                const initialStock = parseInt(display.dataset.currentStock) || 0;
                display.innerText = `Stock: ${initialStock}`;
                display.classList.remove('text-danger');
            });
        }

        // Function to format phone number with country code for WhatsApp
        function formatPhoneForWhatsApp(phone) {
            if (!phone) return '';
            
            // Get the default country code from settings
            const defaultCountryCode = '{{ $all_settings->whatsapp_country_code ?? "+880" }}';
            
            // Clean the phone number (remove spaces, dashes, brackets, etc.)
            let cleanPhone = phone.replace(/[\s\-\(\)\+]/g, '');
            
            // Global country codes for detection (matching backend)
            const globalCountryCodes = [
                // South Asia
                '880', '91', '92', '94', '977', '975', '960', '93',
                // Southeast Asia  
                '60', '62', '63', '65', '66', '84', '855', '856', '95', '673', '670',
                // East Asia
                '86', '81', '82', '852', '853', '886', '976', '850',
                // Middle East
                '971', '966', '965', '974', '973', '968', '967', '964', '963', '98', '90', '972', '970', '962', '961', '357',
                // Central Asia & Caucasus
                '995', '374', '994', '7', '996', '998', '993', '992',
                // Europe
                '1', '44', '49', '33', '39', '34', '31', '32', '41', '43', '48', '420', '421', '36', '40', '359', '30', '351', '46', '47', '45', '358', '380', '375', '372', '371', '370', '353', '354',
                // Africa
                '27', '20', '234', '254', '233', '255', '256', '212', '213', '216', '218', '251',
                // Americas
                '52', '55', '54', '56', '57', '51', '58', '593', '595', '598',
                // Oceania
                '61', '64', '679'
            ];
            
            // Check if phone already has a country code
            for (let code of globalCountryCodes) {
                if (cleanPhone.startsWith(code)) {
                    console.log('📱 Phone already has country code:', code);
                    return cleanPhone; // Already has country code
                }
            }
            
            // If no country code found, add the default one
            const defaultCode = defaultCountryCode.replace('+', '');
            const formattedPhone = defaultCode + cleanPhone;
            
            console.log('📱 Phone formatting:', {
                original: phone,
                cleaned: cleanPhone,
                defaultCode: defaultCode,
                formatted: formattedPhone
            });
            
            return formattedPhone;
        }

        // Function to setup modal button event listeners
        function setupModalButtons() {
            const printBtn = document.getElementById('printInvoiceBtn');
            const whatsappBtn = document.getElementById('sendWhatsAppBtn');
            
            console.log('Setting up modal buttons - Print:', !!printBtn, 'WhatsApp:', !!whatsappBtn);
            
            if (printBtn && !printBtn.hasAttribute('data-listener-added')) {
                printBtn.setAttribute('data-listener-added', 'true');
                printBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('Print button clicked via modal setup');
                    printInvoice();
                });
                console.log('Print button event listener added');
            }
            
            if (whatsappBtn && !whatsappBtn.hasAttribute('data-listener-added')) {
                whatsappBtn.setAttribute('data-listener-added', 'true');
                whatsappBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('WhatsApp button clicked via modal setup');
                    sendWhatsAppNotification();
                });
                console.log('WhatsApp button event listener added');
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            
            // Handle modal events
            const saleModal = document.getElementById('saleCompletionModal');
            if (saleModal) {
                saleModal.addEventListener('hidden.bs.modal', function () {
                    // Clear form when modal is closed without action
                    if (!window.modalActionTaken) {
                        clearPosForm();
                    }
                    window.modalActionTaken = false; // Reset flag
                });
                
                // Add event listeners when modal is shown
                saleModal.addEventListener('shown.bs.modal', function () {
                    console.log('Modal is now shown, adding button event listeners...');
                    setupModalButtons();
                });
            }
            
            // Add event listeners for modal buttons
            console.log('Looking for modal buttons...');
            const printBtn = document.getElementById('printInvoiceBtn');
            const whatsappBtn = document.getElementById('sendWhatsAppBtn');
            
            console.log('Print button element:', printBtn);
            console.log('WhatsApp button element:', whatsappBtn);
            
            if (printBtn) {
                console.log('Print button found, adding event listener');
                printBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('Print button clicked');
                    printInvoice();
                });
            } else {
                console.error('Print button not found!');
            }
            
            if (whatsappBtn) {
                console.log('WhatsApp button found, adding event listener');
                whatsappBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('WhatsApp button clicked');
                    sendWhatsAppNotification();
                });
            } else {
                console.error('WhatsApp button not found!');
            }
            
            // Also try to setup modal buttons immediately
            setTimeout(function() {
                console.log('Attempting to setup modal buttons after delay...');
                setupModalButtons();
            }, 1000);

            // Handle product button clicks
            document.querySelectorAll('.product-card').forEach(card => {
                let clickTimer = null;
                
                card.addEventListener('click', (e) => {
                    e.preventDefault();
                    console.log('Product card clicked:', card.dataset.name);
                    
                    // Single click - show custom price modal
                    if (clickTimer === null) {
                        clickTimer = setTimeout(() => {
                            clickTimer = null;
                            console.log('Single click timeout triggered for:', card.dataset.name);
                            addProduct(
                                card.dataset.id,
                                card.dataset.name,
                                Number(card.dataset.stock || 0),
                                parseFloat(card.dataset.price || 0),
                                parseFloat(card.dataset.basePrice || card.dataset.price || 0),
                                card.dataset.image || ''
                            );
                        }, 200);
                    }
                });

                card.addEventListener('dblclick', (e) => {
                    e.preventDefault();
                    console.log('Product card double-clicked:', card.dataset.name);
                    
                    // Double click - add directly with default price
                    clearTimeout(clickTimer);
                    clickTimer = null;
                    addProductDirectly(
                        card.dataset.id,
                        card.dataset.name,
                        Number(card.dataset.stock || 0),
                        parseFloat(card.dataset.price || 0),
                        card.dataset.image || ''
                    );
                });
            });

            // Exchange modal brand change
            document.getElementById('exchangeBrandSelect').addEventListener('change', function() {
                const brandId = this.value;
                const modelSelect = document.getElementById('exchangeModelSelect');
                if (brandId) {
                    fetch(`/pos/models-by-brand?brand_id=${brandId}`)
                        .then(response => response.json())
                        .then(data => {
                            modelSelect.innerHTML = '<option value="">Select Model</option>';
                            data.forEach(model => {
                                const option = document.createElement('option');
                                option.value = model.id;
                                option.textContent = model.name;
                                modelSelect.appendChild(option);
                            });
                            modelSelect.disabled = false;
                        });
                } else {
                    modelSelect.innerHTML = '<option value="">Select Model</option>';
                    modelSelect.disabled = true;
                }
            });

            // Search and filters
            document.getElementById('productSearch').addEventListener('input', applyFilters);
            document.getElementById('brandSelect').addEventListener('change', function() {
                const brandId = this.value;
                const modelSelect = document.getElementById('modelSelect');
                if (brandId) {
                    fetch(`/pos/models-by-brand?brand_id=${brandId}`)
                        .then(response => response.json())
                        .then(data => {
                            modelSelect.innerHTML = '<option value="">All Models</option>';
                            data.forEach(model => {
                                const option = document.createElement('option');
                                option.value = model.id;
                                option.textContent = model.name;
                                modelSelect.appendChild(option);
                            });
                            modelSelect.disabled = false;
                        });
                } else {
                    modelSelect.innerHTML = '<option value="">All Models</option>';
                    modelSelect.disabled = true;
                }
                applyFilters();
            });
            document.getElementById('modelSelect').addEventListener('change', applyFilters);

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

            // Initialize customer select with Select2 (local data only for now)
            $('#customerSelect').select2({
                placeholder: 'Select Customer or Walk-in',
                allowClear: true,
                data: [], // Will be populated below
                templateResult: function(data) {
                    if (data.id === 'walk_in') {
                        return $('<span><i class="fas fa-user"></i> Walk-in Customer</span>');
                    }
                    return data.text;
                }
            });

            // Prepare customer data for Select2 (customers already loaded globally)
            var customerData = [{
                id: 'walk_in',
                text: 'Walk-in Customer',
                mobile: ''
            }];
            
            // Add all existing customers
            window.customers.forEach(function(customer) {
                customerData.push({
                    id: customer.id,
                    text: customer.name + ' (' + customer.phone + ')',
                    mobile: customer.phone,
                    phone: customer.phone // Add phone as separate property
                });
            });

            // Destroy and reinitialize Select2 with data
            $('#customerSelect').select2('destroy');
            $('#customerSelect').select2({
                placeholder: 'Select Customer or Walk-in',
                allowClear: true,
                data: customerData,
                templateResult: function(data) {
                    if (data.id === 'walk_in') {
                        return $('<span><i class="fas fa-user"></i> Walk-in Customer</span>');
                    }
                    return data.text;
                }
            });

            // Set Walk-in as default and keep it selected
            $('#customerSelect').val('walk_in').trigger('change');

            // Note: We don't auto-select the database walk-in customer to force
            // users to actively choose a real customer for credit transactions
            console.log('✅ POS initialized with Walk-in Customer as default');

            // Customer select change: fetch due amount
            $('#customerSelect').on('change', function() {
                const customerId = $(this).val();
                document.getElementById('customerId').value = customerId;
                const selectedData = $(this).select2('data')[0];
                let mobile = selectedData ? (selectedData.mobile || selectedData.phone) : '';
                
                // If no mobile from Select2 data, try to get from global customers array
                if (!mobile && customerId && customerId !== 'walk_in' && window.customers) {
                    const customer = window.customers.find(c => c.id == customerId);
                    mobile = customer ? customer.phone : '';
                }
                
                document.getElementById('selectedCustomerMobile').value = mobile;
                console.log('Customer selected - ID:', customerId, 'Mobile:', mobile);

                // Enable/disable WhatsApp checkbox based on mobile availability
                const whatsappCheckbox = document.getElementById('sendWhatsApp');
                if (mobile && mobile.trim() !== '' && mobile !== '00000000' && mobile.trim().length > 5) {
                    whatsappCheckbox.disabled = false;
                    whatsappCheckbox.checked = false; // Reset to unchecked when enabled
                } else {
                    whatsappCheckbox.disabled = true;
                    whatsappCheckbox.checked = false;
                }

                if (!customerId) {
                    document.getElementById('payDueContainer').style.display = 'none';
                    document.getElementById('payDue').value = '';
                    const payDueHidden = document.getElementById('payDueHidden');
                    if (payDueHidden) {
                        payDueHidden.value = '';
                        delete payDueHidden.dataset.manuallySet;
                    }
                    return;
                }
                fetch(`/pos/customer-due?customer_id=${customerId}`)
                    .then(response => response.json())
                    .then(data => {
                        console.log("data", data);

                        const due = parseFloat(data.due) || 0;
                        const advance = parseFloat(data.advance) || 0;

                        const dueSection = document.getElementById('customerDueSection');
                        const payDueContainer = document.getElementById('payDueContainer');
                        const payDueInput = document.getElementById('payDue');
                        const payDueHidden = document.getElementById('payDueHidden');
                        const customerDueAlert = document.getElementById('customerDueAlert');

                        if (due > 0 || advance > 0) {
                            if (dueSection) dueSection.style.display = 'block';
                            if (due > 0) {
                                toastr.warning(`Outstanding Due: ${currency} ${due.toFixed(2)}`,
                                    'Customer Due Warning');
                                if (payDueContainer) payDueContainer.style.display = 'block';
                                if (payDueInput) payDueInput.value = due.toFixed(2);
                                // Don't auto-set payDueHidden - only set when user manually pays
                                // if (payDueHidden) payDueHidden.value = due.toFixed(2);
                                if (customerDueAlert) customerDueAlert.innerHTML =
                                    '<i class="fas fa-exclamation-triangle me-2"></i><strong>Outstanding Due: ' + currency + ' <span id="customerDueAmount">' +
                                    due.toFixed(2) + '</span></strong>';
                            } else {
                                if (payDueContainer) payDueContainer.style.display = 'none';
                                if (payDueInput) payDueInput.value = '';
                                if (payDueHidden) {
                                    payDueHidden.value = '';
                                    delete payDueHidden.dataset.manuallySet;
                                }
                                if (customerDueAlert) customerDueAlert.innerHTML =
                                    '<i class="fas fa-exclamation-triangle me-2"></i><strong>No Outstanding Due</strong>';
                            }
                            if (advance > 0) {
                                toastr.info(`Advance Payment: {{ $all_settings->currency ?? 'BDT' }} ${advance.toFixed(2)}`,
                                    'Customer Advance');
                                if (customerDueAlert) customerDueAlert.innerHTML +=
                                    '<br><strong>Advance Payment: ' + currency + ' ' + advance.toFixed(2) +
                                    '</strong>';
                            }
                        } else {
                            if (dueSection) dueSection.style.display = 'none';
                            if (payDueContainer) payDueContainer.style.display = 'none';
                            if (payDueInput) payDueInput.value = '';
                            if (payDueHidden) {
                                payDueHidden.value = '';
                                delete payDueHidden.dataset.manuallySet;
                            }
                        }
                    })
                    .catch(err => {
                        console.error('Error fetching customer due:', err);
                    });
            });

            // Don't sync payDue input to hidden input automatically
            // Only set payDueHidden when user manually clicks Pay button
            // const payDueInput = document.getElementById('payDue');
            // payDueInput.addEventListener('input', function() {
            //     document.getElementById('payDueHidden').value = this.value;
            // });

            // Fullscreen
            document.getElementById('fullscreenBtn').addEventListener('click', toggleFullscreen);
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && document.fullscreenElement)
                    document.exitFullscreen().catch(() => {});
            });

            // Handle fullscreen changes
            document.addEventListener('fullscreenchange', () => {
                const body = document.body;
                const container = document.querySelector('.container-fluid');
                const btn = document.getElementById('fullscreenBtn');

                if (document.fullscreenElement) {
                    // entered fullscreen
                    body.classList.add('fullscreen-mode');
                    container.classList.add('pos-fullscreen');
                    btn.innerHTML = '<i class="fas fa-compress" id="fullscreenIcon"></i>';
                } else {
                    // exited fullscreen
                    body.classList.remove('fullscreen-mode');
                    container.classList.remove('pos-fullscreen');
                    btn.innerHTML = '<i class="fas fa-expand" id="fullscreenIcon"></i>';
                }
            });

            // Multiple payment modal events
            document.getElementById('addPaymentRowBtn').addEventListener('click', addPaymentRow);

            document.getElementById('savePaymentsBtn').addEventListener('click', function() {
                // Set payment method to multiple
                document.getElementById('paymentMethod').value = 'multiple';
                // Close modal and submit
                const modal = bootstrap.Modal.getInstance(document.getElementById('multiplePaymentModal'));
                modal.hide();
                submitForm();
            });

            // Clear and add initial row when modal is shown
            document.getElementById('multiplePaymentModal').addEventListener('shown.bs.modal', function() {
                document.getElementById('paymentsList').innerHTML = '';
                payments = [];
                addPaymentRow();
            });

            // Custom Price Modal keyboard support
            document.getElementById('customPriceModal').addEventListener('keydown', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addProductWithCustomPrice();
                } else if (e.key === 'Escape') {
                    e.preventDefault();
                    closeCustomPriceModal();
                }
            });

            // Auto-calculate quantity limits when price changes
            document.getElementById('customPriceInput').addEventListener('input', function() {
                const maxQty = selectedProductData.remainingStock || 0;
                const quantityInput = document.getElementById('customQuantityInput');
                if (parseInt(quantityInput.value) > maxQty) {
                    quantityInput.value = maxQty;
                }
            });

            // Phone checking functionality
            const phoneInput = document.getElementById('customerNumber');
            const warningText = document.getElementById('phoneExistsWarning');
            const existingCustomerNameSpan = document.getElementById('existingCustomerName');

            if (phoneInput) {
                phoneInput.addEventListener('blur', function() {
                    const phone = phoneInput.value.trim();
                    if (!phone) {
                        warningText.style.display = 'none';
                        existingCustomerNameSpan.textContent = '';
                        return;
                    }
                    fetch("{{ route('customer.checkPhone') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                                'Accept': 'application/json'
                            },
                            body: JSON.stringify({
                                phone: phone
                            })
                        })
                        .then(res => res.json())
                        .then(data => {
                            if (data.exists) {
                                warningText.style.display = 'block';
                                existingCustomerNameSpan.textContent = data.customer.name;
                            } else {
                                warningText.style.display = 'none';
                                existingCustomerNameSpan.textContent = '';
                            }
                        })
                        .catch(err => {
                            console.error('Error checking phone:', err);
                            warningText.style.display = 'none';
                            existingCustomerNameSpan.textContent = '';
                        });
                });
            }

        });

        // Photo handling functions for CPR/ID upload
        function previewCprPhoto(event) {
            const file = event.target.files[0];
            if (file) {
                // Validate file type
                if (!file.type.startsWith('image/')) {
                    alert('Please select a valid image file.');
                    event.target.value = '';
                    return;
                }
                
                // Validate file size (max 5MB)
                if (file.size > 5 * 1024 * 1024) {
                    alert('File size must be less than 5MB.');
                    event.target.value = '';
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('cprPhotoImg').src = e.target.result;
                    document.getElementById('cprPhotoPreview').style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        }

        function removeCprPhoto() {
            document.getElementById('cprPhotoInput').value = '';
            document.getElementById('cprPhotoImg').src = '';
            document.getElementById('cprPhotoPreview').style.display = 'none';
        }

        // Make functions globally accessible
        window.previewCprPhoto = previewCprPhoto;
        window.removeCprPhoto = removeCprPhoto;

        // Save customer fetch
        function saveCustomer() {
            const form = document.getElementById('customerForm');
            const formData = new FormData(form);
            
            // Add the file if selected
            const photoInput = document.getElementById('cprPhotoInput');
            if (photoInput.files[0]) {
                formData.append('cpr_photo', photoInput.files[0]);
            }
            fetch("{{ route('customer.store') }}", {
                    method: "POST",
                    headers: {
                        "X-CSRF-TOKEN": form.querySelector('input[name="_token"]').value,
                        "Accept": "application/json"
                    },
                    body: formData
                })
                .then(res => {
                    if (!res.ok) throw new Error('Server error: ' + res.status);
                    return res.json();
                })
                .then(data => {
                    if (data.customer) {
                        showWarningModal("Success", data.message + (data.photo_saved ? ' Photo uploaded successfully!' : ''));
                        
                        // Add new customer to global customers array for WhatsApp functionality
                        const newCustomerData = {
                            id: data.customer.id,
                            name: data.customer.name,
                            phone: data.customer.number, // Server returns phone as 'number'
                            cpr: data.customer.cpr || '',
                            email: data.customer.email || '',
                            address: data.customer.address || ''
                        };
                        
                        // Update global customers array
                        if (window.customers) {
                            window.customers.push(newCustomerData);
                            console.log('Added customer to global array:', newCustomerData);
                        }
                        
                        // Add new customer to Select2 with proper data structure
                        const customerOption = {
                            id: data.customer.id,
                            text: data.customer.name + ' (' + data.customer.number + ')',
                            mobile: data.customer.number, // For Select2 compatibility
                            phone: data.customer.number   // For WhatsApp functionality
                        };
                        
                        // Get current Select2 data and add new customer
                        const currentData = $('#customerSelect').select2('data');
                        const updatedData = [...currentData, customerOption];
                        
                        // Reinitialize Select2 with updated data
                        $('#customerSelect').select2('destroy');
                        $('#customerSelect').select2({
                            placeholder: 'Select Customer or Walk-in',
                            allowClear: true,
                            data: updatedData,
                            templateResult: function(data) {
                                if (data.id === 'walk_in') {
                                    return $('<span><i class="fas fa-user"></i> Walk-in Customer</span>');
                                }
                                return data.text;
                            }
                        });
                        
                        // Select the newly created customer
                        $('#customerSelect').val(data.customer.id).trigger('change');
                        
                        bootstrap.Modal.getInstance(document.getElementById('customerModal')).hide();
                        form.reset();
                        removeCprPhoto(); // Clear photo preview
                    } else if (data.errors) {
                        showWarningModal("Validation Failed", "Please check the form inputs.");
                        console.log(data.errors);
                    }
                })
                .catch(err => {
                    console.error(err);
                    showWarningModal("Error", "Something went wrong: " + err.message);
                });
        }

        function reloadCustomerSelect(selectedId = null) {
            // Fetch updated customer list from server
            fetch('/api/customers/search?query=', {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(customers => {
                // Prepare customer data for Select2
                var customerData = [{
                    id: 'walk_in',
                    text: 'Walk-in Customer',
                    mobile: ''
                }];
                
                // Add all customers
                customers.forEach(function(customer) {
                    customerData.push({
                        id: customer.id,
                        text: customer.name + ' (' + customer.phone + ')',
                        mobile: customer.phone
                    });
                });

                // Update Select2 with new data
                $('#customerSelect').select2('destroy');
                $('#customerSelect').select2({
                    placeholder: 'Select Customer or Walk-in',
                    allowClear: true,
                    data: customerData,
                    templateResult: function(data) {
                        if (data.id === 'walk_in') {
                            return $('<span><i class="fas fa-user"></i> Walk-in Customer</span>');
                        }
                        return data.text;
                    }
                });

                // Set the selected customer if provided
                if (selectedId) {
                    $('#customerSelect').val(selectedId).trigger('change');
                } else {
                    $('#customerSelect').val('walk_in').trigger('change');
                }
            })
            .catch(error => {
                console.error('Error reloading customers:', error);
                // Fallback to walk-in if reload fails
                $('#customerSelect').val('walk_in').trigger('change');
            });
        }

        // Toggle fullscreen
        async function toggleFullscreen() {
            if (!document.fullscreenElement) {
                try {
                    await document.documentElement.requestFullscreen();
                } catch (err) {
                    console.error('Failed to enter fullscreen:', err);
                }
            } else {
                try {
                    await document.exitFullscreen();
                } catch (err) {
                    console.error('Failed to exit fullscreen:', err);
                }
            }
        }

        // Product filter & search
        function applyFilters() {
            const searchValue = document.getElementById('productSearch').value.toLowerCase();
            const brandId = document.getElementById('brandSelect').value;
            const modelId = document.getElementById('modelSelect').value;
            document.querySelectorAll('#productGrid .col').forEach(col => {
                const card = col.querySelector('.product-card');
                const name = (card.dataset.name || '').toLowerCase();
                const matchesSearch = name.includes(searchValue);
                const matchesBrand = brandId === '' || (card.dataset.brandId || '') === brandId;
                const matchesModel = modelId === '' || (card.dataset.modelId || '') === modelId;
                col.style.display = (matchesSearch && matchesBrand && matchesModel) ? '' : 'none';
            });
        }

        // Add product invoice
        function getInvoiceQty(productId) {
            const row = document.querySelector(`#invoiceItems tr[data-id="${productId}"]`);
            return row ? Number(row.querySelector('.quantity-value').innerText) : 0;
        }

        function updateProductStockDisplay(productId) {
            const productCard = document.querySelector(`.product-card[data-id="${productId}"]`);
            if (!productCard) return;

            const stockDisplay = productCard.parentElement.querySelector('.stock-display');
            if (!stockDisplay) return;

            const initialStock = parseInt(stockDisplay.dataset.currentStock) || 0;
            const currentInvoiceQty = getInvoiceQty(productId);
            const remainingStock = initialStock - currentInvoiceQty;

            stockDisplay.innerText = `Stock: ${remainingStock}`;
            if (remainingStock <= 0) {
                stockDisplay.classList.add('text-danger');
                stockDisplay.innerText += ' (Out of Stock)';
            } else {
                stockDisplay.classList.remove('text-danger');
            }
        }

        // Global variables
        let selectedProductData = {};
        let exchanges = [];
        let payments = [];
        let customers = [];
        
        // Global currency variable
        const currency = '{{ $all_settings->currency ?? "BDT" }}';

        function addProduct(id, name, stock, price, basePrice, image) {
            const customerSelect = document.getElementById('customerSelect');
            const selectedValue = customerSelect.value;
            if (!selectedValue || selectedValue === '') {
                if (notificationSystem) {
                    notificationSystem.showError('Please select a customer before adding products!');
                } else {
                    toastr.error('Please select a customer before adding products!');
                }
                return;
            }

            const productCard = document.querySelector(`.product-card[data-id="${id}"]`);
            const stockDisplay = productCard ? productCard.parentElement.querySelector('.stock-display') : null;
            const initialStock = stockDisplay ? parseInt(stockDisplay.dataset.currentStock) || 0 : stock;
            const currentInvoiceQty = getInvoiceQty(id);
            const remainingStock = initialStock - currentInvoiceQty;

            if (remainingStock < 1) {
                if (notificationSystem) {
                    notificationSystem.showError('Product out of stock!');
                } else {
                    toastr.error('Product out of stock!');
                }
                return;
            }

            // Store product data for the modal
            selectedProductData = {
                id: id,
                name: name,
                stock: stock,
                price: price,
                basePrice: basePrice,
                image: image,
                remainingStock: remainingStock,
                initialStock: initialStock
            };

            // Update modal content
            document.getElementById('customPriceProductName').textContent = name;
            document.getElementById('customPriceDefaultPrice').textContent = currency + ' ' + Number(price).toFixed(2);
            document.getElementById('customPriceInput').value = price;
            document.getElementById('customQuantityInput').value = 1;
            document.getElementById('customQuantityInput').max = remainingStock;

            // Show/hide base price if different from POS price
            const basePriceDiv = document.getElementById('customPriceBasePriceDiv');
            const basePriceSpan = document.getElementById('customPriceBasePrice');
            if (basePrice && basePrice !== price) {
                basePriceSpan.textContent = currency + ' ' + Number(basePrice).toFixed(2);
                basePriceDiv.style.display = 'block';
            } else {
                basePriceDiv.style.display = 'none';
            }

            // Debug logging
            console.log('Opening custom price modal for product:', name, 'Price:', price);
            
            // Show the modal with error handling and fallback
            try {
                const modalElement = document.getElementById('customPriceModal');
                if (modalElement) {
                    // Try Bootstrap 5 first
                    if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                        const modal = new bootstrap.Modal(modalElement);
                        modal.show();
                        
                        // Focus on price input after modal is shown
                        modalElement.addEventListener('shown.bs.modal', function() {
                            document.getElementById('customPriceInput').focus();
                            document.getElementById('customPriceInput').select();
                        }, { once: true });
                    } 
                    // Fallback to jQuery if Bootstrap 5 not available
                    else if (typeof $ !== 'undefined' && $.fn.modal) {
                        $(modalElement).modal('show');
                        
                        // Focus on price input after modal is shown
                        $(modalElement).on('shown.bs.modal', function() {
                            document.getElementById('customPriceInput').focus();
                            document.getElementById('customPriceInput').select();
                        });
                    }
                    // Last resort - show as a simple display
                    else {
                        modalElement.style.display = 'block';
                        modalElement.classList.add('show');
                        document.body.classList.add('modal-open');
                        
                        // Add backdrop
                        const backdrop = document.createElement('div');
                        backdrop.className = 'modal-backdrop fade show';
                        backdrop.id = 'customPriceModalBackdrop';
                        document.body.appendChild(backdrop);
                        
                        // Focus on price input
                        setTimeout(() => {
                            document.getElementById('customPriceInput').focus();
                            document.getElementById('customPriceInput').select();
                        }, 100);
                    }
                } else {
                    console.error('Custom price modal element not found');
                    toastr.error('Modal not found. Please refresh the page.');
                }
            } catch (error) {
                console.error('Error showing modal:', error);
                toastr.error('Error opening price modal: ' + error.message);
            }
        }

        // Function to add product with custom price
        function addProductWithCustomPrice() {
            const customPrice = parseFloat(document.getElementById('customPriceInput').value);
            const quantity = parseInt(document.getElementById('customQuantityInput').value);

            if (!customPrice || customPrice <= 0) {
                toastr.error('Please enter a valid price!');
                return;
            }

            if (!quantity || quantity <= 0) {
                toastr.error('Please enter a valid quantity!');
                return;
            }

            if (quantity > selectedProductData.remainingStock) {
                toastr.error('Quantity exceeds available stock!');
                return;
            }

            const tableBody = document.getElementById('invoiceItems');
            const existing = Array.from(tableBody.children).find(r => r.dataset.id === String(selectedProductData.id));

            if (existing) {
                // Update existing row
                const qtySpan = existing.querySelector('.quantity-value');
                const currentQty = Number(qtySpan.innerText);
                const newQty = currentQty + quantity;
                
                if (newQty > selectedProductData.initialStock) {
                    toastr.error('Total quantity exceeds available stock!');
                    return;
                }
                
                qtySpan.innerText = newQty;
                existing.querySelector('.price').innerHTML = `<strong>${currency} ${customPrice.toFixed(2)}</strong>`;
                existing.querySelector('.subtotal').innerHTML = `<strong class="text-primary">${currency} ${(newQty * customPrice).toFixed(2)}</strong>`;
                // Update the base price to use custom price for transaction
                existing.dataset.basePrice = customPrice;
            } else {
                // Create new row
                const row = document.createElement('tr');
                row.dataset.id = selectedProductData.id;
                row.dataset.basePrice = customPrice; // Store custom price for transaction
                row.innerHTML = `
                    <td>${escapeHtml(selectedProductData.name)}</td>
                    <td>${selectedProductData.stock}</td>
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-primary" onclick="changeQuantity(this,-1)">-</button>
                            <span class="btn btn-sm btn-outline-primary quantity-value">${quantity}</span>
                            <button class="btn btn-sm btn-outline-primary" onclick="changeQuantity(this,1)">+</button>
                        </div>
                    </td>
                    <td><strong class="price">${currency} ${customPrice.toFixed(2)}</strong></td>
                    <td><strong class="text-primary subtotal">${currency} ${(quantity * customPrice).toFixed(2)}</strong></td>
                    <td><button class="btn btn-danger btn-sm" onclick="removeItem(this)"><i class="fas fa-trash"></i></button></td>
                `;
                tableBody.appendChild(row);
            }

            updateSummary();
            updateProductStockDisplay(selectedProductData.id);

            // Hide the modal
            closeCustomPriceModal();

            // Show success message
            toastr.success(`${selectedProductData.name} added with custom price ${currency} ${customPrice.toFixed(2)}`);
        }

        // Function to add product directly with default price (for double-click)
        function addProductDirectly(id, name, stock, price, image) {
            const customerSelect = document.getElementById('customerSelect');
            const selectedValue = customerSelect.value;
            if (!selectedValue || selectedValue === '') {
                toastr.error('Please select a customer before adding products!');
                return;
            }

            const productCard = document.querySelector(`.product-card[data-id="${id}"]`);
            const stockDisplay = productCard ? productCard.parentElement.querySelector('.stock-display') : null;
            const initialStock = stockDisplay ? parseInt(stockDisplay.dataset.currentStock) || 0 : stock;
            const currentInvoiceQty = getInvoiceQty(id);
            const remainingStock = initialStock - currentInvoiceQty;

            if (remainingStock < 1) {
                toastr.error('Product out of stock!');
                return;
            }

            // Get base price from product card
            const basePrice = productCard ? parseFloat(productCard.dataset.basePrice) || price : price;

            const tableBody = document.getElementById('invoiceItems');
            const existing = Array.from(tableBody.children).find(r => r.dataset.id === String(id));

            let newQty;
            if (existing) {
                const qtySpan = existing.querySelector('.quantity-value');
                newQty = Number(qtySpan.innerText) + 1;
                if (initialStock - newQty < 0) {
                    toastr.error('Product out of stock!');
                    return;
                }
                qtySpan.innerText = newQty;
                const unitPrice = parseFloat(existing.querySelector('.price').innerText.replace(currency, '').trim()) || price;
                existing.querySelector('.subtotal').innerText = currency + ' ' + (newQty * unitPrice).toFixed(2);
            } else {
                const row = document.createElement('tr');
                row.dataset.id = id;
                row.dataset.basePrice = basePrice; // Store base price for transaction
                row.innerHTML = `
                    <td>${escapeHtml(name)}</td>
                    <td>${stock}</td>
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-primary" onclick="changeQuantity(this,-1)">-</button>
                            <span class="btn btn-sm btn-outline-primary quantity-value">1</span>
                            <button class="btn btn-sm btn-outline-primary" onclick="changeQuantity(this,1)">+</button>
                        </div>
                    </td>
                    <td><strong class="price">${currency} ${Number(price).toFixed(2)}</strong></td>
                    <td><strong class="text-primary subtotal">${currency} ${Number(price).toFixed(2)}</strong></td>
                    <td><button class="btn btn-danger btn-sm" onclick="removeItem(this)"><i class="fas fa-trash"></i></button></td>
                `;
                tableBody.appendChild(row);
                newQty = 1;
            }
            updateSummary();
            updateProductStockDisplay(id);
            toastr.success(`${name} added with default price`);
        }

        // Function to reset price to default in the modal
        function useDefaultPrice() {
            if (selectedProductData.price) {
                document.getElementById('customPriceInput').value = selectedProductData.price;
                document.getElementById('customPriceInput').focus();
            }
        }

        function closeCustomPriceModal() {
            const modalElement = document.getElementById('customPriceModal');
            if (modalElement) {
                // Try Bootstrap 5 first
                if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                    const modal = bootstrap.Modal.getInstance(modalElement);
                    if (modal) {
                        modal.hide();
                    }
                } 
                // Fallback to jQuery
                else if (typeof $ !== 'undefined' && $.fn.modal) {
                    $(modalElement).modal('hide');
                }
                // Manual close
                else {
                    modalElement.style.display = 'none';
                    modalElement.classList.remove('show');
                    document.body.classList.remove('modal-open');
                    
                    // Remove backdrop
                    const backdrop = document.getElementById('customPriceModalBackdrop');
                    if (backdrop) {
                        backdrop.remove();
                    }
                }
            }
        }

        // Test function for debugging - can be called from browser console
        window.testCustomPriceModal = function() {
            console.log('Testing custom price modal...');
            console.log('Bootstrap available:', typeof bootstrap !== 'undefined');
            console.log('jQuery available:', typeof $ !== 'undefined');
            
            const modalElement = document.getElementById('customPriceModal');
            console.log('Modal element found:', !!modalElement);
            
            if (modalElement) {
                // Test with dummy data
                selectedProductData = {
                    id: '1',
                    name: 'Test Product',
                    stock: 10,
                    price: 100,
                    basePrice: 95,
                    image: '',
                    remainingStock: 10,
                    initialStock: 10
                };
                
                addProduct('1', 'Test Product', 10, 100, 95, '');
            }
        };

        // Test function for sale completion modal
        window.testSaleModal = function() {
            console.log('Testing sale completion modal...');
            
            // Set test data
            window.currentSaleData = { sale_id: 123 };
            
            // Show modal
            showSaleCompletionModal({ sale_id: 123 });
        };

        // Test function for sale completion sound
        window.testSaleSound = function() {
            console.log('Testing sale completion sound...');
            if (notificationSystem) {
                notificationSystem.saleComplete(
                    'Sale Completed Successfully!',
                    'Test Invoice #12345 - Customer: Test Customer - Amount: ' + currency + ' 150.00'
                );
            } else {
                console.error('notificationSystem not available');
            }
        };

        // Test functions for buttons
        window.testPrintButton = function() {
            console.log('Testing print button...');
            window.currentSaleData = { sale_id: 123 };
            printInvoice();
        };

        window.testWhatsAppButton = function() {
            console.log('Testing WhatsApp button...');
            window.currentSaleData = { sale_id: 123 };
            sendWhatsAppNotification();
        };

        // Global function check
        window.checkFunctions = function() {
            console.log('Function availability:');
            console.log('printInvoice:', typeof printInvoice);
            console.log('sendWhatsAppNotification:', typeof sendWhatsAppNotification);
            console.log('showSaleCompletionModal:', typeof showSaleCompletionModal);
            console.log('Bootstrap:', typeof bootstrap !== 'undefined');
            console.log('Current sale data:', window.currentSaleData);
        };

        function removeItem(button) {
            const row = button.closest('tr');
            const productId = row.dataset.id;
            row.remove();
            updateSummary();
            updateProductStockDisplay(productId);
        }

        function changeQuantity(button, delta) {
            const row = button.closest('tr');
            const productId = row.dataset.id;
            const qtySpan = row.querySelector('.quantity-value');
            const currentQty = Number(qtySpan.innerText);
            let newQty = currentQty + delta;

            const productCard = document.querySelector(`.product-card[data-id="${productId}"]`);
            const stockDisplay = productCard ? productCard.parentElement.querySelector('.stock-display') : null;
            const initialStock = stockDisplay ? parseInt(stockDisplay.dataset.currentStock) || 0 : 0;

            if (newQty < 1) {
                if (delta < 0) {
                    toastr.error('Minimum quantity is 1');
                }
                return;
            }

            if (newQty > initialStock) {
                toastr.error('Cannot exceed available stock');
                return;
            }

            qtySpan.innerText = newQty;
            const price = parseFloat(row.querySelector('.price').innerText.replace(currency, '').trim()) || 0;
            row.querySelector('.subtotal').innerText = currency + ' ' + (newQty * price).toFixed(2);
            updateSummary();
            updateProductStockDisplay(productId);
        }

        function updateSummary() {
            const rows = document.querySelectorAll('#invoiceItems tr');
            let totalItems = 0,
                totalAmount = 0,
                totalDiscount = 0;
            rows.forEach(row => {
                const qtySpan = row.querySelector('.quantity-value');
                const priceSpan = row.querySelector('.price');
                if (!qtySpan || !priceSpan) return;
                const qty = Number(qtySpan.innerText) || 0;
                const price = parseFloat(priceSpan.innerText.replace(currency, '').trim()) || 0;
                totalItems += qty;
                totalAmount += price * qty;
            });

            // Add exchange discount
            const exchangeDiscount = exchanges.reduce((sum, exchange) => sum + exchange.price, 0);
            totalDiscount += exchangeDiscount;

            const grandTotal = totalAmount - totalDiscount;
            const totalItemsEl = document.getElementById('totalItems');
            const totalAmountEl = document.getElementById('totalAmount');
            const totalDiscountEl = document.getElementById('totalDiscount');
            const grandTotalEl = document.getElementById('grandTotal');
            const cashAmountEl = document.getElementById('cashAmount');
            const payAllAmountEl = document.getElementById('payAllAmount');

            if (totalItemsEl) totalItemsEl.innerText = totalItems;
            if (totalAmountEl) totalAmountEl.innerText = totalAmount.toFixed(2);
            if (totalDiscountEl) totalDiscountEl.innerText = totalDiscount.toFixed(2);
            if (grandTotalEl) grandTotalEl.innerText = grandTotal.toFixed(2);
            if (cashAmountEl) cashAmountEl.innerText = grandTotal.toFixed(2);
            if (payAllAmountEl) payAllAmountEl.innerText = grandTotal.toFixed(2);
        }

        // Minimal helper alert/modal replacement
        function showWarningModal(title, message) {
            alert(title + ': ' + message);
        }

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#39;'
            };
            return String(text).replace(/[&<>"']/g, function(m) {
                return map[m];
            });
        }


        // Validate credit payment - prevent walk-in customers from using credit
        function validateCreditPayment() {
            const customerSelect = document.getElementById('customerSelect');
            const selectedCustomerId = customerSelect ? customerSelect.value : 'walk_in';
            
            console.log('🔍 Credit payment validation - Customer ID:', selectedCustomerId);
            
            // Check if walk-in customer is selected
            if (selectedCustomerId === 'walk_in') {
                // Show error notification
                if (typeof notificationSystem !== 'undefined') {
                    notificationSystem.showError(
                        'Credit Payment Not Allowed',
                        'Walk-in customers cannot make credit purchases. Please select a proper customer for credit transactions.',
                        5000
                    );
                } else if (typeof toastr !== 'undefined') {
                    toastr.error(
                        'Walk-in customers cannot make credit purchases. Please select a proper customer for credit transactions.',
                        'Credit Payment Not Allowed',
                        {
                            timeOut: 5000,
                            positionClass: 'toast-top-center'
                        }
                    );
                } else {
                    alert('⚠️ Credit Payment Not Allowed\n\nWalk-in customers cannot make credit purchases.\nPlease select a proper customer for credit transactions.');
                }
                
                console.log('❌ Credit payment blocked for walk-in customer');
                return false; // Prevent credit payment
            }
            
            // Customer is selected, allow credit payment
            console.log('✅ Credit payment allowed for customer ID:', selectedCustomerId);
            setPaymentMethod('credit');
            submitForm();
        }

        function setPaymentMethod(method) {
            document.getElementById('paymentMethod').value = method;
        }

        // Add exchange item
        function addExchange() {
            const brandSelect = document.getElementById('exchangeBrandSelect');
            const brandInput = document.getElementById('exchangeBrandInput');
            const modelSelect = document.getElementById('exchangeModelSelect');
            const modelInput = document.getElementById('exchangeModelInput');
            const price = parseFloat(document.getElementById('exchangePrice').value);
            const imei = document.getElementById('exchangeImei').value;

            let brandId = brandSelect.value;
            let brandName = brandInput.value.trim();
            let modelId = modelSelect.value;
            let modelName = modelInput.value.trim();

            if ((!brandId && !brandName) || (!modelId && !modelName) || !price || !imei) {
                alert('Please fill all fields');
                return;
            }

            if (!brandName && brandId) {
                brandName = brandSelect.options[brandSelect.selectedIndex].text;
            }
            if (!modelName && modelId) {
                modelName = modelSelect.options[modelSelect.selectedIndex].text;
            }

            const exchangeIndex = exchanges.length;
            exchanges.push({
                brand_id: brandId,
                mobile_model_id: modelId,
                price: price,
                imei: imei,
                brand_name: brandName,
                model_name: modelName
            });

            // Add to product list with note
            const tableBody = document.getElementById('invoiceItems');
            const row = document.createElement('tr');
            row.dataset.id = 'exchange_' + exchangeIndex;
            row.innerHTML = `
                <td>Exchanged Product: ${brandName} ${modelName} (IMEI: ${imei})</td>
                <td>1</td>
                <td>1</td>
                <td><strong class="price">${currency} 0.00</strong></td>
                <td><strong class="text-primary subtotal">${currency} 0.00</strong></td>
                <td><button class="btn btn-danger btn-sm" onclick="removeExchangeItem(this, ${exchangeIndex})"><i class="fas fa-trash"></i></button></td>
            `;
            tableBody.appendChild(row);

            updateExchangeList();
            updateSummary();

            // Reset form
            document.getElementById('exchangeForm').reset();
            modelSelect.disabled = true;
        }

        // Update exchange list display
        function updateExchangeList() {
            const list = document.getElementById('exchangeList');
            list.innerHTML = '';
            exchanges.forEach((exchange, index) => {
                const li = document.createElement('li');
                li.className = 'list-group-item d-flex justify-content-between align-items-center';
                li.innerHTML = `
                    ${exchange.brand_name} ${exchange.model_name} - IMEI: ${exchange.imei} - ${currency} ${exchange.price.toFixed(2)}
                    <button class="btn btn-danger btn-sm" onclick="removeExchange(${index})">Remove</button>
                `;
                list.appendChild(li);
            });
        }

        // Remove exchange item
        function removeExchange(index) {
            exchanges.splice(index, 1);
            // Remove from invoice table
            const row = document.querySelector(`#invoiceItems tr[data-id="exchange_${index}"]`);
            if (row) row.remove();
            updateExchangeList();
            updateSummary();
        }

        // Remove exchange item from invoice table
        function removeExchangeItem(button, index) {
            const row = button.closest('tr');
            row.remove();
            removeExchange(index);
        }

        // Pay customer due
        function payCustomerDue() {
            const customerId = document.getElementById('customerSelect').value;
            const amount = parseFloat(document.getElementById('payDue').value);
            if (!customerId || !amount || amount <= 0) {
                toastr.error('Please enter a valid amount to pay.');
                return;
            }

            // Set the payDueHidden value and mark as manually set for this sale
            const payDueHidden = document.getElementById('payDueHidden');
            if (payDueHidden) {
                payDueHidden.value = amount.toFixed(2);
                payDueHidden.dataset.manuallySet = 'true';
            }
            fetch("{{ route('customer.payDue') }}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('input[name="_token"]').value,
                    },
                    body: JSON.stringify({
                        customer_id: customerId,
                        amount: amount,
                        type: 'due_payment',
                        notes: 'Paid via POS',
                    }),
                })
                .then(response => response.json())
                .then(data => {
                    if (data.message) {
                        toastr.success(data.message);
                        // Refresh customer due
                        fetch(`/pos/customer-due?customer_id=${customerId}`)
                            .then(response => response.json())
                            .then(data => {
                                const due = parseFloat(data.due) || 0;
                                const advance = parseFloat(data.advance) || 0;
                                const payDueContainer = document.getElementById('payDueContainer');
                                const payDueInput = document.getElementById('payDue');
                                const payDueHidden = document.getElementById('payDueHidden');
                                if (due > 0) {
                                    toastr.warning(`Outstanding Due: ${currency} ${due.toFixed(2)}`,
                                        'Customer Due Warning');
                                    if (payDueContainer) payDueContainer.style.display = 'block';
                                    if (payDueInput) payDueInput.value = due.toFixed(2);
                                    if (payDueHidden) payDueHidden.value = due.toFixed(2);
                                } else {
                                    if (payDueContainer) payDueContainer.style.display = 'none';
                                    if (payDueInput) payDueInput.value = '';
                                    if (payDueHidden) payDueHidden.value = '';
                                }
                                if (advance > 0) {
                                    toastr.info(`Advance Payment: ${currency} ${advance.toFixed(2)}`, 'Customer Advance');
                                }
                            });
                    } else {
                        toastr.error('Failed to record payment.');
                    }
                })
                .catch(err => {
                    console.error('Error paying due:', err);
                    toastr.error('An error occurred while processing the payment.');
                });
        }

        // Payment management functions
        function addPaymentRow() {
            const paymentsList = document.getElementById('paymentsList');
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>
                    <select class="form-select form-select-sm payment-method">
                        <option value="cash">Cash</option>
                        <option value="card">Card</option>
                        <option value="bank_transfer">Bank Transfer</option>
                    </select>
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm payment-amount" placeholder="Amount" min="0" step="0.01">
                </td>
                <td>
                    <button class="btn btn-sm btn-outline-danger" type="button" onclick="removePaymentRow(this)">Remove</button>
                </td>
            `;
            paymentsList.appendChild(row);
            updatePayments();
        }

        function removePaymentRow(button) {
            button.closest('tr').remove();
            updatePayments();
        }

        function updatePayments() {
            const rows = document.querySelectorAll('#paymentsList tr');
            payments = [];
            rows.forEach(row => {
                const method = row.querySelector('.payment-method').value;
                const amount = parseFloat(row.querySelector('.payment-amount').value) || 0;
                if (amount > 0) {
                    payments.push({
                        method,
                        amount
                    });
                }
            });
            updateSummary();
        }

        // Add event listeners for payment changes
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('payment-amount')) {
                updatePayments();
            }
        });

        document.addEventListener('change', function(e) {
            if (e.target.classList.contains('payment-method')) {
                updatePayments();
            }
        });
    </script>

    <!-- Multiple Payment Modal -->
    <div class="modal fade" id="multiplePaymentModal" tabindex="-1" aria-labelledby="multiplePaymentModalLabel"
        aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="multiplePaymentModalLabel">Multiple Payments</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <table class="table table-sm" id="paymentsTable">
                        <thead>
                            <tr>
                                <th>Payment Method</th>
                                <th>Amount</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="paymentsList"></tbody>
                    </table>
                    <button class="btn btn-sm btn-outline-primary" type="button" id="addPaymentRowBtn">Add
                        Payment</button>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="savePaymentsBtn">Save Payments</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Invoice Modal -->
    <div class="modal fade" id="invoiceModal" tabindex="-1" aria-labelledby="invoiceModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="invoiceModalLabel">Invoice</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="invoiceModalBody" style="overflow-y:auto; max-height:80vh;">
                    <!-- Invoice HTML will be injected here -->
                </div>
            </div>
        </div>
    </div>

    <!-- Sale Completion Modal -->
    <div class="modal fade" id="saleCompletionModal" tabindex="-1" aria-labelledby="saleCompletionModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title" id="saleCompletionModalLabel">
                        <i class="fas fa-check-circle mr-2"></i>Sale Completed Successfully!
                    </h5>
                </div>
                <div class="modal-body text-center">
                    <div class="mb-3">
                        <i class="fas fa-receipt fa-3x text-success mb-3"></i>
                        <h6>Invoice #<span id="completedSaleId"></span></h6>
                        <p class="text-muted">Customer: <span id="completedCustomerName"></span></p>
                        <p class="text-muted">Amount: <span id="completedAmount"></span></p>
                    </div>
                    <div class="alert alert-info">
                        <small><i class="fas fa-info-circle mr-1"></i>What would you like to do next?</small>
                    </div>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-primary btn-lg mr-3" id="printInvoiceBtn" onclick="printInvoice()">
                        <i class="fas fa-print mr-2"></i>Print Invoice
                    </button>
                    <button type="button" class="btn btn-success btn-lg" id="sendWhatsAppBtn" onclick="sendWhatsAppNotification()">
                        <i class="fab fa-whatsapp mr-2"></i>Send WhatsApp
                    </button>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <section id="printArea"></section>
@endsection
