@extends('layouts.app')
@section('title', 'New Purchase')
@section('content')
<h4 class="mb-3">New Purchase from Flour Mill</h4>
<div class="card">
    <div class="card-body">
        <form action="{{ route('purchases.store') }}" method="POST">
            @csrf
            <div class="row g-3 mb-3">
                <div class="col-md-4">
                    <label for="supplier_id" class="form-label">Supplier (Mill)</label>
                    <select name="supplier_id" id="supplier_id" class="form-select" required>
                        <option value="">Select Supplier</option>
                        @foreach($suppliers as $s)
                            <option value="{{ $s->id }}">{{ $s->name }} (Due: Rs. {{ number_format($s->balance, 2) }})</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="date" class="form-label">Date</label>
                    <input type="date" name="date" id="date" class="form-control" value="{{ date('Y-m-d') }}" required>
                </div>
                <div class="col-md-4">
                    <label for="notes" class="form-label">Notes</label>
                    <input type="text" name="notes" id="notes" class="form-control">
                </div>
            </div>

            <h6>Items (Bags from Mill)</h6>
            <table class="table table-sm" id="itemsTable">
                <thead>
                    <tr><th>Category</th><th>Weight</th><th>Bags</th><th>Price/Bag</th><th>Subtotal</th><th></th></tr>
                </thead>
                <tbody></tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" class="text-end fw-bold">Grand Total:</td>
                        <td class="fw-bold fs-5" id="grandTotal">Rs. 0.00</td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
            <button type="button" class="btn btn-sm btn-outline-success mb-3" id="addItem"><i class="bi bi-plus"></i> Add Item</button>

            <div class="row g-3">
                <div class="col-md-3">
                    <label for="paid_amount" class="form-label">Amount Paying Now</label>
                    <input type="number" step="0.01" name="paid_amount" id="paid_amount" class="form-control" value="0">
                    <small class="text-muted">Remaining added to supplier balance</small>
                </div>
            </div>

            <div class="mt-3">
                <button type="submit" class="btn btn-primary">Record Purchase</button>
                <a href="{{ route('purchases.index') }}" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

@push('scripts')
<script>
const categories = @json($categories);
const productsByCategory = {};
@json($products).forEach(p => {
    if (!productsByCategory[p.category_id]) productsByCategory[p.category_id] = [];
    productsByCategory[p.category_id].push({
        id: p.id,
        weight_label: p.weight ? p.weight.label : '-',
        price: p.price,
        stock: p.stock,
    });
});

let rowIndex = 0;

function addItemRow() {
    const tbody = document.querySelector('#itemsTable tbody');
    const tr = document.createElement('tr');

    let catOptions = '<option value="">-- Category --</option>';
    categories.forEach(c => { catOptions += `<option value="${c.id}">${c.name}</option>`; });

    tr.innerHTML = `
        <td><select class="form-select form-select-sm cat-select" required>${catOptions}</select></td>
        <td><select name="items[${rowIndex}][product_id]" class="form-select form-select-sm weight-select" required><option value="">-- Weight --</option></select></td>
        <td><input type="number" name="items[${rowIndex}][bags]" class="form-control form-control-sm bags-input" min="1" step="1" required></td>
        <td><input type="number" step="0.01" name="items[${rowIndex}][price_per_bag]" class="form-control form-control-sm ppb-input" min="0" required></td>
        <td class="subtotal text-nowrap">Rs. 0.00</td>
        <td><button type="button" class="btn btn-sm btn-outline-danger remove-row"><i class="bi bi-trash"></i></button></td>
    `;
    tbody.appendChild(tr);
    rowIndex++;

    const catSelect = tr.querySelector('.cat-select');
    const weightSelect = tr.querySelector('.weight-select');
    const bags = tr.querySelector('.bags-input');
    const ppb = tr.querySelector('.ppb-input');

    catSelect.addEventListener('change', function() {
        weightSelect.innerHTML = '<option value="">-- Weight --</option>';
        if (this.value && productsByCategory[this.value]) {
            productsByCategory[this.value].forEach(p => {
                weightSelect.innerHTML += `<option value="${p.id}">${p.weight_label}</option>`;
            });
        }
        calcTotal();
    });

    bags.addEventListener('input', () => calcRow(tr));
    ppb.addEventListener('input', () => calcRow(tr));
    tr.querySelector('.remove-row').addEventListener('click', () => { tr.remove(); calcTotal(); });
}

function calcRow(tr) {
    const bags = parseInt(tr.querySelector('.bags-input').value) || 0;
    const ppb = parseFloat(tr.querySelector('.ppb-input').value) || 0;
    tr.querySelector('.subtotal').textContent = 'Rs. ' + (bags * ppb).toFixed(2);
    calcTotal();
}

function calcTotal() {
    let total = 0;
    document.querySelectorAll('#itemsTable tbody tr').forEach(tr => {
        const bags = parseInt(tr.querySelector('.bags-input').value) || 0;
        const ppb = parseFloat(tr.querySelector('.ppb-input').value) || 0;
        total += bags * ppb;
    });
    document.getElementById('grandTotal').textContent = 'Rs. ' + total.toFixed(2);
}

document.getElementById('addItem').addEventListener('click', addItemRow);
addItemRow();
</script>
@endpush
@endsection
