@extends('layouts.admin')

@section('title', 'Create Purchase Order')

@section('content')
<div class="tw-migrated space-y-4">
    <x-ui.page-header title="Create Purchase Order">
        <x-slot:actions>
            <x-ui.button href="{{ route('admin.purchase-orders.index') }}" variant="secondary">
                <i class="bi bi-arrow-left"></i> Back
            </x-ui.button>
        </x-slot:actions>
    </x-ui.page-header>

    @if($errors->any())
        <x-ui.alert type="danger">
            <ul class="mb-0">@foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach</ul>
        </x-ui.alert>
    @endif

    @if($suppliers->isEmpty())
        <x-ui.alert type="warning">
            Add a supplier first: <a href="{{ route('admin.suppliers.index') }}">Suppliers</a>
        </x-ui.alert>
    @endif

    <x-ui.card title="Purchase Order Details">
        <p class="text-muted">One PO can include <strong>one or many products</strong>. Use “Add product line” for more items.</p>

        <form method="post" action="{{ route('admin.purchase-orders.store') }}" id="poForm">
            @csrf
            <input type="hidden" name="company_id" value="{{ $company->id }}">

            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <label class="admin-form-label">Supplier *</label>
                    <select name="supplier_id" class="form-select admin-form-control" required @disabled($suppliers->isEmpty())>
                        <option value="">Select supplier</option>
                        @foreach($suppliers as $s)
                            <option value="{{ $s->id }}" @selected(old('supplier_id') == $s->id)>{{ $s->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="admin-form-label">Receive into Location *</label>
                    <select name="location_id" class="form-select admin-form-control" required>
                        @foreach($locations as $loc)
                            <option value="{{ $loc->id }}" @selected(old('location_id', ($loc->type==='warehouse' && $loc->is_default) ? $loc->id : null) == $loc->id)>
                                {{ $loc->name }} ({{ ucfirst($loc->type) }})
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="admin-form-label">Expected Date</label>
                    <input type="date" name="expected_date" class="form-control admin-form-control" value="{{ old('expected_date') }}">
                </div>
                <div class="col-12">
                    <label class="admin-form-label">Notes</label>
                    <textarea name="notes" class="form-control admin-form-control" rows="2" placeholder="Optional notes">{{ old('notes') }}</textarea>
                </div>
            </div>

            <div class="mb-2 flex items-center justify-between">
                <h5 class="mb-0">Products</h5>
                <button type="button" class="tw-btn tw-btn-outline tw-btn-sm" id="addPoLine">
                    <i class="bi bi-plus-lg"></i> Add product line
                </button>
            </div>

            <div class="tw-table-wrap">
                <table class="tw-table align-middle" id="poItemsTable">
                    <thead>
                        <tr>
                            <th style="min-width:280px;">Product *</th>
                            <th style="width:120px;">Qty *</th>
                            <th style="width:140px;">Unit Cost *</th>
                            <th style="width:140px;">Line Total</th>
                            <th style="width:60px;"></th>
                        </tr>
                    </thead>
                    <tbody id="poItemsBody">
                        <tr class="item-row">
                            <td>
                                <select name="items[0][product_id]" class="form-select admin-form-control product-select" required>
                                    <option value="">Search product…</option>
                                    @foreach($products as $p)
                                        <option value="{{ $p->id }}"
                                            data-cost="{{ $p->purchase_price ?? 0 }}"
                                            @selected(old('items.0.product_id') == $p->id)>
                                            {{ $p->name }}@if($p->sku) ({{ $p->sku }})@endif
                                        </option>
                                    @endforeach
                                </select>
                            </td>
                            <td>
                                <input type="number" min="1" name="items[0][quantity]" class="form-control admin-form-control qty-input" required value="{{ old('items.0.quantity', 1) }}">
                            </td>
                            <td>
                                <input type="number" step="0.01" min="0" name="items[0][unit_cost]" class="form-control admin-form-control unit-cost" required value="{{ old('items.0.unit_cost') }}">
                            </td>
                            <td class="line-total fw-semibold">₹0.00</td>
                            <td>
                                <button type="button" class="btn btn-outline-danger btn-sm remove-line" title="Remove" style="display:none;">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <th colspan="3" class="text-end">Estimated Total</th>
                            <th id="poGrandTotal">₹0.00</th>
                            <th></th>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <button type="submit" class="tw-btn-primary mt-2" @disabled($suppliers->isEmpty())>
                <i class="bi bi-check-circle"></i> Create Draft PO
            </button>
        </form>
    </x-ui.card>
</div>

@php
$productOptions = $products->map(fn ($p) => [
    'id' => $p->id,
    'text' => $p->name . ($p->sku ? ' ('.$p->sku.')' : ''),
    'cost' => (float) ($p->purchase_price ?? 0),
])->values();
@endphp

@push('scripts')
<script>
(function () {
    const products = @json($productOptions);
    let idx = 1;
    const body = document.getElementById('poItemsBody');
    const grandEl = document.getElementById('poGrandTotal');
    const addBtn = document.getElementById('addPoLine');

    function escapeHtml(s) {
        return String(s).replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
    }
    function money(n) { return '₹' + (Number(n) || 0).toFixed(2); }
    function optionsHtml(selected) {
        let html = '<option value="">Search product…</option>';
        products.forEach(p => {
            const sel = selected && String(selected) === String(p.id) ? ' selected' : '';
            html += `<option value="${p.id}" data-cost="${p.cost}"${sel}>${escapeHtml(p.text)}</option>`;
        });
        return html;
    }
    function recalc() {
        let grand = 0;
        body.querySelectorAll('.item-row').forEach((row) => {
            const qty = parseFloat(row.querySelector('.qty-input')?.value) || 0;
            const cost = parseFloat(row.querySelector('.unit-cost')?.value) || 0;
            const line = qty * cost;
            grand += line;
            const lt = row.querySelector('.line-total');
            if (lt) lt.textContent = money(line);
        });
        if (grandEl) grandEl.textContent = money(grand);
        const showRemove = body.querySelectorAll('.item-row').length > 1;
        body.querySelectorAll('.remove-line').forEach((btn) => { btn.style.display = showRemove ? '' : 'none'; });
    }
    function bindRow(row) {
        const sel = row.querySelector('.product-select');
        sel?.addEventListener('change', function () {
            const cost = this.options[this.selectedIndex]?.getAttribute('data-cost');
            const costInput = row.querySelector('.unit-cost');
            if (cost != null && costInput && (!costInput.value || costInput.value === '0')) {
                costInput.value = cost;
            }
            recalc();
        });
        row.querySelectorAll('.qty-input, .unit-cost').forEach((el) => el.addEventListener('input', recalc));
    }
    const first = body?.querySelector('.item-row');
    if (first) bindRow(first);
    recalc();
    addBtn?.addEventListener('click', function () {
        const tr = document.createElement('tr');
        tr.className = 'item-row';
        tr.innerHTML = `<td><select name="items[${idx}][product_id]" class="form-select admin-form-control product-select" required>${optionsHtml()}</select></td>
            <td><input type="number" min="1" name="items[${idx}][quantity]" class="form-control admin-form-control qty-input" required value="1"></td>
            <td><input type="number" step="0.01" min="0" name="items[${idx}][unit_cost]" class="form-control admin-form-control unit-cost" required></td>
            <td class="line-total fw-semibold">₹0.00</td>
            <td><button type="button" class="btn btn-outline-danger btn-sm remove-line"><i class="bi bi-trash"></i></button></td>`;
        body.appendChild(tr);
        bindRow(tr);
        idx++;
        recalc();
    });
    body?.addEventListener('click', function (e) {
        const btn = e.target.closest('.remove-line');
        if (!btn) return;
        if (body.querySelectorAll('.item-row').length <= 1) return;
        btn.closest('.item-row')?.remove();
        recalc();
    });
})();
</script>
@endpush
@endsection
