@extends('layouts.app')

@section('title', 'Create Purchase Order')

@section('content')
    <div class="mb-4">
        <h4 class="mb-0">New Purchase Order</h4>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 small">
                <li class="breadcrumb-item"><a href="{{ url('/') }}">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="{{ route('purchase-orders.index') }}">Purchase Orders</a></li>
                <li class="breadcrumb-item active">New Order</li>
            </ol>
        </nav>
    </div>

    <form action="{{ route('purchase-orders.store') }}" method="POST">
        @csrf
        <div class="row g-4">
            <div class="col-lg-12">
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-body p-4">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label fw-bold small text-muted text-uppercase">Supplier <span
                                        class="text-danger">*</span></label>
                                <select name="partner_id" class="form-select form-select-lg" required>
                                    <option value="">Select Supplier...</option>
                                    @foreach($partners as $partner)
                                        <option value="{{ $partner->id }}">{{ $partner->name }} ({{ $partner->code }})</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold small text-muted text-uppercase">Order Date <span
                                        class="text-danger">*</span></label>
                                <input type="date" name="order_date" class="form-control form-control-lg" required
                                    value="{{ date('Y-m-d') }}">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold small text-muted text-uppercase">Expected Delivery</label>
                                <input type="date" name="expected_date" class="form-control form-control-lg">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-bottom py-3">
                        <h6 class="mb-0 fw-bold">Order Items</h6>
                    </div>
                    <div class="card-body p-0">
                        <table class="table align-middle mb-0" id="itemsTable">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-4">Product</th>
                                    <th style="width: 150px;">Quantity</th>
                                    <th style="width: 150px;">Unit Price</th>
                                    <th style="width: 150px;">Subtotal</th>
                                    <th class="text-end pe-4"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="item-row">
                                    <td class="ps-4">
                                        <select name="items[0][product_id]" class="form-select product-select" required>
                                            <option value="">Choose product...</option>
                                            @foreach($products as $product)
                                                <option value="{{ $product->id }}" data-price="{{ $product->price ?? 0 }}">
                                                    {{ $product->name }}</option>
                                            @endforeach
                                        </select>
                                    </td>
                                    <td><input type="number" name="items[0][quantity]" class="form-control qty-input"
                                            required min="1" value="1"></td>
                                    <td><input type="number" name="items[0][unit_price]" class="form-control price-input"
                                            required step="0.01"></td>
                                    <td><input type="text" class="form-control-plaintext fw-bold subtotal-display" readonly
                                            value="$0.00"></td>
                                    <td class="text-end pe-4">
                                        <button type="button" class="btn btn-light btn-sm remove-row"><i
                                                class="bi bi-x"></i></button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="card-footer bg-white border-top py-3">
                        <button type="button" class="btn btn-outline-primary btn-sm" id="addRow">
                            <i class="bi bi-plus-lg me-1"></i> Add Another Product
                        </button>
                    </div>
                </div>

                <div class="mt-4 d-flex justify-content-between align-items-center">
                    <div class="text-muted small">
                        * All inventory updates occur only after the order is marked as <strong>"Received"</strong>.
                    </div>
                    <div class="d-flex gap-3 align-items-center">
                        <div class="me-4 text-end">
                            <div class="small text-muted text-uppercase fw-bold">Total Amount</div>
                            <div class="fs-3 fw-bold text-primary" id="grandTotal">$0.00</div>
                        </div>
                        <a href="{{ route('purchase-orders.index') }}" class="btn btn-light px-4">Cancel</a>
                        <button type="submit" class="btn btn-primary px-5 shadow-sm">Generate PO</button>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            let rowIdx = 1;
            const table = document.getElementById('itemsTable').querySelector('tbody');

            document.getElementById('addRow').addEventListener('click', function () {
                const newRow = document.querySelector('.item-row').cloneNode(true);
                newRow.querySelectorAll('input').forEach(i => i.value = i.classList.contains('qty-input') ? 1 : '');
                newRow.querySelector('select').value = '';
                newRow.querySelector('.subtotal-display').value = '$0.00';

                newRow.querySelectorAll('[name*="[0]"]').forEach(el => {
                    el.name = el.name.replace('[0]', '[' + rowIdx + ']');
                });

                table.appendChild(newRow);
                rowIdx++;
                attachListeners(newRow);
            });

            function attachListeners(row) {
                const qty = row.querySelector('.qty-input');
                const price = row.querySelector('.price-input');
                const subtotal = row.querySelector('.subtotal-display');
                const product = row.querySelector('.product-select');
                const removeBtn = row.querySelector('.remove-row');

                const updateRow = () => {
                    const total = (parseFloat(qty.value) || 0) * (parseFloat(price.value) || 0);
                    subtotal.value = '$' + total.toFixed(2);
                    updateGrandTotal();
                };

                qty.addEventListener('input', updateRow);
                price.addEventListener('input', updateRow);
                product.addEventListener('change', function () {
                    const p = product.options[product.selectedIndex].dataset.price;
                    if (p) price.value = p;
                    updateRow();
                });

                removeBtn.addEventListener('click', function () {
                    if (table.querySelectorAll('.item-row').length > 1) {
                        row.remove();
                        updateGrandTotal();
                    }
                });
            }

            function updateGrandTotal() {
                let total = 0;
                document.querySelectorAll('.item-row').forEach(row => {
                    const q = row.querySelector('.qty-input').value || 0;
                    const p = row.querySelector('.price-input').value || 0;
                    total += q * p;
                });
                document.getElementById('grandTotal').innerText = '$' + total.toFixed(2);
            }

            attachListeners(document.querySelector('.item-row'));
        });
    </script>
@endsection