@extends('layouts.pos')

@section('title', 'POS - ' . \App\Models\Setting::get('site_name', 'KiyoKart') . ' Admin')

@section('content')
    <div class="pos-container">
        <!-- Header -->
        <header class="pos-header">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="pos-title">
                    <i class="bi bi-cash-stack"></i> {{ \App\Models\Setting::get('site_name', 'KiyoKart') }} POS
                </h1>
                <div class="d-flex align-items-center gap-3">
                    @if(isset($posLocations) && $posLocations->count())
                    <form method="post" action="{{ route('admin.locations.set-current') }}" class="d-flex align-items-center gap-2" id="posStoreForm">
                        @csrf
                        <label class="text-white small mb-0" for="posLocationSelect">Store</label>
                        <select name="location_id" id="posLocationSelect" class="form-select form-select-sm" style="width:auto;min-width:180px;" onchange="this.form.submit()">
                            @foreach($posLocations as $loc)
                                <option value="{{ $loc->id }}" @selected(($currentLocationId ?? null) == $loc->id)>{{ $loc->name }}</option>
                            @endforeach
                        </select>
                    </form>
                    @endif
                    <button class="btn btn-sm btn-outline-light" id="heldBillsToggle" title="Held Bills">
                        <i class="bi bi-list"></i> Held Bills
                        <span class="badge bg-warning text-dark ms-1" id="heldBillsCount" style="display: none;">0</span>
                    </button>
                    <div class="online-status" id="onlineStatus">
                        <i class="bi bi-wifi"></i> <span>Online</span>
                    </div>
                    <button class="btn btn-sm btn-outline-light" onclick="window.close()">
                        <i class="bi bi-x-lg"></i> Close
                    </button>
                </div>
            </div>
        </header>

        <div class="pos-main">
            <!-- Left Panel: Customer & Products -->
            <div class="pos-left-panel">
                <!-- Top Row: Customer, Product Search & Salesman Side by Side -->
                <div class="pos-top-row row">
                    <!-- Customer Selection - All fields inline -->
                    <div class="pos-section customer-section col-md-12">
                        <h3 class="section-title">
                            <i class="bi bi-person"></i> Customer
                        </h3>
                        <div class="customer-fields-inline">
                            <div class="row g-2 mb-2">
                                <div class="col-6">
                                    <label class="form-label small mb-0">Mobile</label>
                                    <div class="input-group">
                                        <span class="input-group-text">+91</span>
                                        <input type="text" id="customerMobile" class="form-control form-control-sm" placeholder="10 digits" maxlength="10" autocomplete="off" pattern="[6-9]\d{9}" inputmode="numeric" required tabindex="1">
                                    </div>
                                </div>
                                <div class="col-6">
                                    <label class="form-label small mb-0">Name</label>
                                    <input type="text" id="customerName" class="form-control form-control-sm" placeholder="Customer Name" autocomplete="off" tabindex="2">
                                </div>
                            </div>
                            <div id="customerExtraFields" class="customer-extra-fields" style="display: none;">
                                <div class="row g-2 mb-2">
                                    <div class="col-6">
                                        <label class="form-label small mb-0">Email</label>
                                        <input type="email" id="newCustomerEmail" class="form-control form-control-sm" placeholder="Optional">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label small mb-0">GST No.</label>
                                        <input type="text" id="newCustomerGst" class="form-control form-control-sm" placeholder="Optional" maxlength="15">
                                    </div>
                                </div>
                                <div class="row g-2 mb-2">
                                    <div class="col-6">
                                        <label class="form-label small mb-0">Type</label>
                                        <select id="newCustomerType" class="form-select form-select-sm">
                                            <option value="retail" selected>Retail</option>
                                            <option value="wholesale">Wholesale</option>
                                        </select>
                                    </div>
                                    <div class="col-6 customer-create-col">
                                        <button type="button" class="btn btn-success btn-sm" id="createCustomerBtn">
                                            <i class="bi bi-person-plus"></i> Create
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary btn-sm" id="clearCustomerBtn" title="Clear">
                                            <i class="bi bi-x"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div id="customerInfo" class="customer-info mt-2" style="display: none;">
                            <span id="customerType" class="badge bg-secondary"></span>
                            <button type="button" class="btn btn-link btn-sm p-0 ms-2" onclick="posSystem.clearCustomer()">Clear</button>
                        </div>
                        <div id="customerDropdown" class="customer-dropdown" style="display: none;"></div>
                    </div>
                </div>

                <!-- Product List -->
                <div class="pos-section product-list-section">
                    <!-- Product Search -->
                    <div class="pos-section mb-2">
                        <div class="search-input-group">
                            <input type="text" 
                                   id="productSearch" 
                                   class="form-control form-control-sm" 
                                   placeholder="Search or scan barcode..."
                                   autocomplete="off"
                                   tabindex="3">
                            <button class="btn btn-outline-secondary btn-sm" id="clearSearchBtn">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    </div>                 
                    <div id="productList" class="product-list">
                        <div class="text-center text-muted p-4">
                            <i class="bi bi-search"></i> Search for products
                        </div>
                    </div>
                </div>
            </div>

            <!-- Center Panel: Cart -->
            <div class="pos-center-panel">
                <div class="pos-section cart-section">
                    <h3 class="section-title">
                        <i class="bi bi-cart"></i> Cart
                        <span class="badge bg-primary" id="cartCount">0</span>
                    </h3>

                    <div id="cartItems" class="cart-items">
                        <div class="text-center text-muted p-4">
                            <i class="bi bi-cart-x"></i> Cart is empty
                        </div>
                    </div>

                    <div class="customization-section mt-3">
                        <h5 class="my-2">
                            <i class="bi bi-pencil-square"></i> Customization Charges
                        </h5>
                        <input type="number"
                               id="customizationCharges"
                               class="form-control form-control-sm"
                               placeholder="0.00"
                               step="0.01"
                               min="0"
                               value="0"
                               tabindex="5">
                        <small class="text-muted">Enter additional customization charges if any</small>
                    </div>

                    <div class="cart-totals">
                        <div class="total-row">
                            <span>Subtotal:</span>
                            <span id="cartSubtotal">₹0.00</span>
                        </div>
                        <div class="total-row">
                            <span>Tax:</span>
                            <span id="cartTax">₹0.00</span>
                        </div>
                        <div class="total-row discount-row" id="discountRow" style="display: none;">
                            <span>Discount:</span>
                            <span id="cartDiscount" style="color: var(--pos-success);">-₹0.00</span>
                        </div>
                        <div class="total-row shipping-row" id="shippingRow" style="display: none;">
                            <span>Shipping:</span>
                            <span id="cartShipping">₹0.00</span>
                        </div>
                        <div class="total-row customization-row" id="customizationRow" style="display: none;">
                            <span>Customization:</span>
                            <span id="cartCustomization">₹0.00</span>
                        </div>
                        <div class="total-row total-final">
                            <span>Total:</span>
                            <span id="cartTotal">₹0.00</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Panel: Pickup Type, Salesman, Payment -->
            <div class="pos-right-panel">
                <div class="pos-section payment-section">
                    <div class="delivery-type-section" id="deliveryTypeSection">
                        <h5 class="delivery-type-title">
                            <i class="bi bi-bag-check"></i> Pickup Type
                        </h5>
                        <div class="delivery-type-options">
                            <label class="delivery-type-option">
                                <input type="radio" name="deliveryType" value="store_pickup" checked>
                                <span><i class="bi bi-shop"></i> Store Pickup</span>
                            </label>
                            <label class="delivery-type-option">
                                <input type="radio" name="deliveryType" value="courier">
                                <span><i class="bi bi-box-seam"></i> Courier</span>
                            </label>
                        </div>
                        <small class="text-muted" id="deliveryTypeNote">Default: Store Pickup</small>
                        <div class="selected-address-summary mt-2" id="selectedAddressSummary" style="display: none;">
                            <div class="small text-muted">Delivery Address:</div>
                            <div id="selectedAddressText" class="fw-semibold"></div>
                            <button type="button" class="btn btn-link p-0" id="changeAddressBtn">Change address</button>
                        </div>
                        <div class="select-address-prompt mt-2" id="selectAddressPrompt" style="display: none;">
                            <button type="button" class="btn btn-sm btn-outline-primary" id="selectAddressBtn">
                                <i class="bi bi-geo-alt"></i> Select Delivery Address
                            </button>
                        </div>
                    </div>

                    <div class="pos-section salesman-section">
                        <h3 class="section-title">
                            <i class="bi bi-person-badge"></i> Salesman
                        </h3>
                        <select id="salesmanSelect" class="form-select form-select-sm" tabindex="4">
                            <option value="">Loading staff...</option>
                        </select>
                    </div>

                    <div class="payment-amounts mt-3">
                        <h5 class="my-2">
                            <i class="bi bi-cash-coin"></i> Payment
                        </h5>
                        <div id="paymentStorePickupBlock">
                            <div class="payment-amount">
                                <label class="small-label">
                                    <i class="bi bi-wallet2"></i> Cash Amount
                                </label>
                                <input type="number"
                                       id="cashAmount"
                                       class="form-control form-control-sm"
                                       placeholder="0.00"
                                       step="0.01"
                                       min="0"
                                       tabindex="6">
                            </div>
                            <div class="payment-amount">
                                <label class="small-label">
                                    <i class="bi bi-credit-card"></i> Card / UPI Amount
                                </label>
                                <input type="number"
                                       id="cardAmount"
                                       class="form-control form-control-sm"
                                       placeholder="0.00"
                                       step="0.01"
                                       min="0"
                                       tabindex="7">
                            </div>
                            <div class="quick-amounts" id="quickAmountButtons" aria-label="Quick amount controls">
                                <button type="button" class="quick-amount-btn quick-amount-btn-exact" data-quick-amount="exact">Exact</button>
                                <button type="button" class="quick-amount-btn" data-quick-amount="50">+50</button>
                                <button type="button" class="quick-amount-btn" data-quick-amount="100">+100</button>
                                <button type="button" class="quick-amount-btn" data-quick-amount="200">+200</button>
                                <button type="button" class="quick-amount-btn" data-quick-amount="500">+500</button>
                                <button type="button" class="quick-amount-btn" data-quick-amount="1000">+1000</button>
                            </div>
                            <div class="payment-amount">
                                <label class="small-label">Total Received</label>
                                <div class="total-received-display" id="totalReceived">₹0.00</div>
                            </div>
                            <div class="change-amount">
                                <label class="small-label">Change (Cash)</label>
                                <div class="change-display" id="changeAmount">₹0.00</div>
                            </div>
                        </div>
                        <div id="paymentCourierBlock" class="mt-2" style="display: none;">
                            <div class="payment-amount mb-2">
                                <span class="small-label"><i class="bi bi-bank"></i> Offline Payment</span>
                                <p class="small text-muted mb-1">Upload payment screenshot (required for courier)</p>
                                <input type="file"
                                       id="paymentScreenshot"
                                       class="form-control form-control-sm"
                                       accept="image/jpeg,image/png,image/gif,image/webp"
                                       tabindex="6">
                            </div>
                        </div>
                        <div class="payment-info">
                            <div class="info-row">
                                <small>Items: <strong id="cartItemCount">0</strong></small>
                                <small>Qty: <strong id="cartTotalQty">0</strong></small>
                            </div>
                        </div>
                        <button type="button" class="btn btn-warning btn-lg w-100 mb-2" id="holdBillBtn" disabled tabindex="8">
                            <i class="bi bi-pause-circle"></i> Hold Bill
                        </button>
                        <button type="button" class="btn btn-success btn-lg w-100" id="completeSaleBtn" disabled tabindex="9">
                            <i class="bi bi-check-circle"></i> Complete Sale
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Held Bills Panel -->
        <div class="held-bills-panel" id="heldBillsPanel" style="display: none;">
            <div class="held-bills-header">
                <h4>
                    <i class="bi bi-pause-circle"></i> Held Bills
                </h4>
                <button class="btn btn-sm btn-outline-secondary" onclick="posSystem.toggleHeldBillsPanel()">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <div class="held-bills-content">
                <div id="heldBillsList">
                    <div class="text-center text-muted p-3">
                        <i class="bi bi-inbox"></i><br>No held bills
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Receipt Modal -->
    <div class="modal fade" id="receiptModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-white">Receipt</h5>
                    <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal"><i class="bi-x-lg"></i></button>
                </div>
                <div class="modal-body" id="receiptContent">
                    <!-- Receipt content will be inserted here -->
                </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="printReceiptBtn">
                        <i class="bi bi-printer"></i> Print
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Address Selection Modal -->
    <div class="modal fade" id="addressModal" tabindex="-1" aria-labelledby="addressModalTitle" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content address-modal">
                <div class="modal-header">
                    <h5 class="modal-title" id="addressModalTitle">
                        <i class="bi bi-geo-alt-fill me-1"></i> Select Delivery Address
                    </h5>
                    <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal" aria-label="Close"><i class="bi-x-lg"></i></button>
                </div>
                <div class="modal-body address-modal-body">
                    <div class="address-modal-grid">
                        <section class="address-saved-pane">
                            <div class="address-pane-head">
                                <span><i class="bi bi-bookmark-check"></i> Saved addresses</span>
                                <button type="button" class="btn btn-link btn-sm p-0" id="refreshAddressesBtn" title="Refresh">
                                    <i class="bi bi-arrow-clockwise"></i>
                                </button>
                            </div>
                            <div id="addressList" class="address-list">
                                <div class="address-loading">
                                    <div class="spinner"></div>
                                    <span>Loading addresses…</span>
                                </div>
                            </div>
                        </section>

                        <section class="address-new-pane">
                            <div class="address-pane-head">
                                <span><i class="bi bi-plus-circle"></i> Add new address</span>
                            </div>
                            <form id="addressForm" autocomplete="off" class="address-form">
                                <div class="row g-2">
                                    <div class="col-md-6">
                                        <label class="form-label small" for="addrName">Name</label>
                                        <input type="text" class="form-control form-control-sm" id="addrName" autocomplete="off" required>
                                        <small class="text-danger" id="addrNameError" style="display: none;"></small>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label small" for="addrMobile">Mobile</label>
                                        <div class="input-group">
                                            <span class="input-group-text">+91</span>
                                            <input type="text" class="form-control form-control-sm" id="addrMobile" placeholder="10 digits" autocomplete="off" maxlength="10" inputmode="numeric" pattern="[6-9]\d{9}" required>
                                        </div>
                                        <small class="text-danger" id="addrMobileError" style="display: none;"></small>
                                    </div>
                                    <div class="col-12">
                                        <label class="form-label small" for="addrLine1">Address Line 1</label>
                                        <input type="text" class="form-control form-control-sm" id="addrLine1" placeholder="House / Flat, Street" autocomplete="off" required>
                                        <small class="text-danger" id="addrLine1Error" style="display: none;"></small>
                                    </div>
                                    <div class="col-12">
                                        <label class="form-label small" for="addrLine2">Address Line 2 <span class="text-muted fw-normal">(optional)</span></label>
                                        <input type="text" class="form-control form-control-sm" id="addrLine2" placeholder="Landmark, Area" autocomplete="off">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small" for="addrCountry">Country</label>
                                        <select class="form-select form-select-sm" id="addrCountry" required>
                                            <option value="">Select country</option>
                                        </select>
                                        <small class="text-danger" id="addrCountryError" style="display: none;"></small>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small" for="addrState">State</label>
                                        <select class="form-select form-select-sm" id="addrState" disabled required>
                                            <option value="">Select state</option>
                                        </select>
                                        <small class="text-danger" id="addrStateError" style="display: none;"></small>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small" for="addrCity">City</label>
                                        <select class="form-select form-select-sm" id="addrCity" disabled required>
                                            <option value="">Select city</option>
                                        </select>
                                        <small class="text-danger" id="addrCityError" style="display: none;"></small>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label small" for="addrPin">PIN Code</label>
                                        <input type="text" class="form-control form-control-sm" id="addrPin" placeholder="6 digits" autocomplete="off" maxlength="6" required>
                                        <small class="text-danger" id="addrPinError" style="display: none;"></small>
                                    </div>
                                </div>
                            </form>
                        </section>
                    </div>
                </div>
                <div class="modal-footer address-modal-footer">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" form="addressForm" class="btn btn-primary btn-sm" id="saveAddressBtn">
                        <i class="bi bi-check2"></i> Save &amp; Select
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Discount / Complete Order OTP Modal -->
    <div class="modal fade" id="discountOtpModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">OTP Verification</h5>
                    <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal" aria-label="Close"><i class="bi-x-lg"></i></button>
                </div>
                <div class="modal-body">
                    <div class="mb-2 text-muted">
                        Enter the 6-digit OTP sent to Store MD/Manager to complete the order.
                    </div>
                    <div class="mb-3">
                        <label for="discountOtpInput" class="form-label" id="discountOtpTimer">OTP ( expires in 5:00 )</label>
                        <input type="text"
                               class="form-control"
                               id="discountOtpInput"
                               inputmode="numeric"
                               autocomplete="one-time-code"
                               maxlength="6"
                               placeholder="000000">
                        <div id="discountOtpError" class="text-danger mt-2" style="display: none;"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" id="resendDiscountOtpBtn">Resend OTP</button>
                    <button type="button" class="btn btn-primary" id="verifyDiscountOtpBtn">Verify</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <!-- Pass Company Settings to JavaScript -->
    <script>
        window.POSCompanySettings = {
            name: @json(\App\Models\Setting::get('site_name', 'KiyoKart')),
            address: @json(\App\Models\Setting::get('site_address', '')),
            phone: @json(\App\Models\Setting::get('site_phone', ''))
        };
    </script>

    <!-- POS JavaScript -->
    <script src="{{ asset('js/pos-db.js') }}?v={{ time() }}"></script>
    <script src="{{ asset('js/pos.js') }}?v={{ time() }}"></script>

    <script>
        // Register Service Worker (offline cache + background sync). Requires HTTPS in production; ensure APP_URL is set correctly on server.
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('{{ asset("sw-pos.js") }}', { scope: '/admin/pos/' })
                .then(registration => console.log('Service Worker registered'))
                .catch(error => console.log('Service Worker registration failed:', error));
        }
    </script>
@endpush
