/home/awneajlw/www/safeeyesjewelers.com/resources/views/admin/subAdmin/index.blade.php
@include('admin.component.header')
@include('admin.component.topnav')
@include('admin.component.navbar')

<div class="content-body">
    <div class="container-fluid mt-3">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="row justify-content-center">
                        <div class="col-md-10 p-5">
                            <h4>{{ __('SE.sale_form') }}</h4>

                            <!-- Inventory Form -->
                            <form action="{{ route('sales.store') }}" method="POST" id="saleForm">
                                @csrf
<input type="hidden" name="direction" value="horizontal">
                                <div class="form-group">
                                    <label for="language">{{ __('SE.language_select') }}</label>
                                    <select name="language" class="form-select" required>
                                        <option selected disabled>Select Language</option>
                                        <option value="arabic">{{ __('SE.arabic') }}</option>
                                        <option value="english">{{ __('SE.english') }}</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label for="buyer_name">{{ __('SE.buyer_name') }}</label>
                                    <input type="text" name="buyer_name" class="form-control" required>
                                </div>

                                <div class="form-group">
                                    <label for="vat_no">{{ __('SE.vat_number') }}</label>
                                    <input type="text" name="vat_no" id="vat_no" placeholder="VAT Number (Optional)" class="form-control">
                                </div>

                                <!-- Product Selection Rows -->
                                <div id="productRows">
                                    <div class="product-row row mb-3">
                                        <div class="col-md-3">
                                            <label>Product</label>
                                            <input type="text" class="form-control inventory-input" placeholder="Search Product..." required>
                                            <input type="hidden" name="inventory_ids[]" class="inventory-id">
                                            <datalist id="inventoryList">
                                                @foreach ($inventories as $inventory)
                                                    <option value="{{ $inventory->name }} (Qty: {{ $inventory->quantity }})"
                                                            data-id="{{ $inventory->id }}"
                                                            data-name="{{ $inventory->name }}"
                                                            data-price="{{ $inventory->price }}"
                                                            data-qty="{{ $inventory->quantity }}">
                                                    </option>
                                                @endforeach
                                            </datalist>
                                        </div>
                                        <div class="col-md-2">
                                            <label>Quantity</label>
                                            <input type="number" name="quantities[]" class="form-control qty-input" min="1" disabled>
                                        </div>
                                        <div class="col-md-2">
                                            <label>Price</label>
                                            <input type="number" name="prices[]" class="form-control price-input" disabled>
                                            
                                        </div>
                                        <div class="col-md-2">
                                            <label>VAT (15%)</label>
                                            <input type="text" class="form-control vat-amount" readonly>
                                        </div>
                                        <div class="col-md-2">
                                            <label>Final Price</label>
                                            <input type="text" class="form-control final-price" readonly>
                                        </div>
                                        <div class="col-md-1 d-flex align-items-end">
                                            <button type="button" class="btn btn-danger remove-row" style="display:none;">X</button>
                                        </div>
                                    </div>
                                </div>

                                <button type="button" id="addRowBtn" class="btn btn-success mb-3">+ Add More</button>

                                <div class="row mt-3">
                                    <div class="col-md-4 offset-md-5">
                                        <button type="submit" id="createBillBtn" class="btn btn-primary mt-4" disabled>{{ __('SE.create_bill') }}</button>
                                    </div>
                                    <div class="col-md-3">
                                        <label>Subtotal:</label>
                                        <span class="form-control" id="subtotal_price">0.00</span>

                                        <label>Total VAT:</label>
                                        <span class="form-control" id="vat_price">0.00</span>

                                        <label>Grand Total:</label>
                                        <span class="form-control" id="total_price">0.00</span>
                                    </div>
                                </div>
                            </form>

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

        {{-- Bills Table --}}
        @php
            use Illuminate\Support\Facades\DB;
            use Illuminate\Support\Facades\Auth;

            $from_date = request('from_date');
            $to_date   = request('to_date');
            $userBranchId = Auth::user()->branch_id; // ✅ logged-in user's branch

            $query = "SELECT s.id, s.vat_no, s.price, s.total_price, 
                             s.buyer_name, s.direction, s.language, s.qr_ksa, 
                             s.created_at, s.updated_at, 
                             b.name AS branch_name
                      FROM sales s
                      LEFT JOIN branches b ON s.branch_id = b.id
                      WHERE s.branch_id = ? ";  // ✅ Restrict by branch

            $bindings = [$userBranchId];

            if ($from_date && $to_date) {
                $query .= " AND DATE(s.created_at) BETWEEN ? AND ? ";
                $bindings[] = $from_date;
                $bindings[] = $to_date;
            }

            $query .= " ORDER BY s.id DESC"; // latest first
            $sales = DB::select($query, $bindings);
        @endphp

        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="row mt-4">
                        <div class="col">
                            <div class="card" style="overflow:auto; width:100% !important;">
                                <h3 class="text-center m-2">Invoice Record</h3>
                                <div class="card-header">
                                    <form method="GET" style="display:flex; gap:10px; flex-wrap:wrap;">
                                        <input type="date" name="from_date" value="{{ request('from_date') }}" class="form-control" style="width:200px;">
                                        <input type="date" name="to_date" value="{{ request('to_date') }}" class="form-control" style="width:200px;">
                                        <button type="submit" class="btn btn-primary"><i class="fas fa-filter"></i> Filter</button>
                                        <a href="{{ url()->current() }}" class="btn btn-secondary">Reset</a>
                                    </form>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover sale-listing table-listing" style="width:100%;">
                                            <thead>
                                                <tr>
                                                    <th>S.No</th>
                                                    <th>VAT No</th>
                                                    <th>Buyer Name</th>
                                                    <th>Price</th>
                                                    <th>Total Price</th>
                                                    <th>Branch</th> {{-- ✅ Branch Name --}}
                                                    <th>Direction</th>
                                                    <th>Language</th>
                                                    <th>QR KSA</th>
                                                    <th>Created At</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($sales as $sale)
                                                    <tr>
                                                        <td>{{ $loop->iteration }}</td> {{-- ✅ Auto S.No --}}
                                                        <td>{{ $sale->vat_no }}</td>
                                                        <td>{{ $sale->buyer_name }}</td>
                                                        <td>{{ $sale->price }}</td>
                                                        <td>{{ $sale->total_price }}</td>
                                                        <td>{{ $sale->branch_name ?? 'N/A' }}</td> {{-- ✅ Branch Name --}}
                                                        <td>{{ $sale->direction }}</td>
                                                        <td>{{ $sale->language }}</td>
                                                        <td>{{ $sale->qr_ksa }}</td>
                                                        <td>{{ \Carbon\Carbon::parse($sale->created_at)->format('d-m-Y H:i') }}</td>
                                                        <td>
                                                            <a href="{{ url('invoice/'.$sale->id) }}" 
                                                               class="btn btn-sm btn-info" 
                                                               target="_blank">
                                                                <i class="fas fa-file-invoice"></i> Invoice
                                                            </a>
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@include('admin.component.footer')

{{-- DataTables --}}
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js" defer></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js" defer></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">

<script>
    // ✅ DataTable
    $(document).ready(function() {
        $('.sale-listing').DataTable({
            order: [[0, 'asc']] // S.No ascending
        });
    });
</script>



{{-- DataTables --}}
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js" defer></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js" defer></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">

<script>
    function updateTotals() {
        let subtotal = 0, totalVat = 0;

        document.querySelectorAll('.product-row').forEach(row => {
            let fp = parseFloat(row.querySelector('.final-price').value) || 0;
            let vat = parseFloat(row.querySelector('.vat-amount').value) || 0;

            subtotal += (fp - vat);
            totalVat += vat;
        });

        let total = subtotal + totalVat;

        document.getElementById('subtotal_price').innerText = subtotal.toFixed(2);
        document.getElementById('vat_price').innerText = totalVat.toFixed(2);
        document.getElementById('total_price').innerText = total.toFixed(2);

        document.getElementById("createBillBtn").disabled = total <= 0;
    }

    function bindRowEvents(row) {
        const input = row.querySelector('.inventory-input');
        const hiddenId = row.querySelector('.inventory-id');
        const qtyInput = row.querySelector('.qty-input');
        const priceInput = row.querySelector('.price-input');
        const vatField = row.querySelector('.vat-amount');
        const finalPrice = row.querySelector('.final-price');

        input.setAttribute("list", "inventoryList");

        input.addEventListener('change', function() {
            let val = this.value;
            let option = [...document.querySelectorAll('#inventoryList option')].find(opt => opt.value === val);

            if (option) {
                let qty = parseInt(option.dataset.qty);
                let price = parseFloat(option.dataset.price);
                let id = option.dataset.id;
                let name = option.dataset.name;

                if (qty === 0) {
                    alert("This product is out of stock and cannot be added.");
                    this.value = "";
                    hiddenId.value = "";
                    return;
                }

                this.value = name;
                hiddenId.value = id;

                priceInput.value = price;
                priceInput.disabled = false;

                qtyInput.disabled = false;
                qtyInput.max = qty;
                qtyInput.value = 1;

                let vat = (price * 0.15).toFixed(2);
                vatField.value = vat;
                finalPrice.value = (price + parseFloat(vat)).toFixed(2);

                updateTotals();
            }
        });

        qtyInput.addEventListener('input', function() {
            let price = parseFloat(priceInput.value) || 0;
            let qty = parseInt(this.value) || 0;
            let vat = (price * qty * 0.15).toFixed(2);

            vatField.value = vat;
            finalPrice.value = (price * qty + parseFloat(vat)).toFixed(2);

            updateTotals();
        });

        priceInput.addEventListener('input', function() {
            let qty = parseInt(qtyInput.value) || 0;
            let price = parseFloat(this.value) || 0;
            let vat = (price * qty * 0.15).toFixed(2);

            vatField.value = vat;
            finalPrice.value = (price * qty + parseFloat(vat)).toFixed(2);

            updateTotals();
        });

        row.querySelector('.remove-row').addEventListener('click', function() {
            row.remove();
            updateTotals();
        });
    }

    bindRowEvents(document.querySelector('.product-row'));

    document.getElementById('addRowBtn').addEventListener('click', function() {
        let row = document.querySelector('.product-row').cloneNode(true);
        row.querySelectorAll('input').forEach(input => input.value = '');
        row.querySelector('.qty-input').disabled = true;
        row.querySelector('.price-input').disabled = true;
        row.querySelector('.remove-row').style.display = 'block';

        document.getElementById('productRows').appendChild(row);
        bindRowEvents(row);
    });

    // ✅ Initialize DataTable
    $(document).ready(function() {
        $('.sale-listing').DataTable();
    });
</script>