@extends('layouts.vendor')

@section('title', 'Order Management')
@section('header_title', 'Order Management')

@section('content')
    <div style="display: flex; justify-content: space-between; gap: 1rem; margin-bottom: 1.5rem;">
        <form method="GET" style="display: flex; gap: 0.75rem; flex: 1; max-width: 650px;">
            <input name="search" value="{{ request('search') }}" placeholder="Order, customer or phone" style="margin: 0;">
            <select name="status" style="margin: 0; max-width: 170px;"><option value="">All statuses</option>@foreach(['pending', 'confirmed', 'ready', 'completed', 'cancelled'] as $status)<option value="{{ $status }}" @selected(request('status') === $status)>{{ ucfirst($status) }}</option>@endforeach</select>
            <button class="btn btn-primary">Filter</button>
        </form>
        <button onclick="document.getElementById('orderModal').style.display='block'" class="btn btn-primary"><i class="fa-solid fa-plus"></i> New Order</button>
    </div>

    <div class="card">
        <table>
            <thead><tr><th>Order</th><th>Customer</th><th>Items</th><th>Total</th><th>Progress</th><th>Actions</th></tr></thead>
            <tbody>
                @forelse($orders as $order)
                    <tr>
                        <td><strong>{{ $order->order_number }}</strong><div style="color: var(--text-muted); font-size: 0.8rem;">{{ $order->ordered_at->format('d M Y, h:i A') }}</div></td>
                        <td>{{ $order->customer_name }}<div style="color: var(--text-muted); font-size: 0.8rem;">{{ $order->customer_phone ?: $order->customer_email }}</div></td>
                        <td>{{ $order->items->sum('quantity') }} units<div style="color: var(--text-muted); font-size: 0.8rem;">{{ $order->items->pluck('item_name')->take(2)->join(', ') }}</div></td>
                        <td style="color: var(--success); font-weight: 700;">₹{{ number_format($order->total, 2) }}<div style="font-size: 0.75rem; color: var(--text-muted);">{{ ucfirst($order->payment_status) }}</div></td>
                        <td><span class="badge {{ $order->status === 'cancelled' ? 'badge-danger' : 'badge-success' }}">{{ ucfirst($order->status) }}</span></td>
                        <td>
                            <form method="POST" action="{{ route('vendor.orders.update', $order->id) }}" style="display: flex; gap: 0.5rem; align-items: center;">
                                @csrf @method('PATCH')
                                <select name="status" style="margin: 0; min-width: 115px;">@foreach(['pending', 'confirmed', 'ready', 'completed', 'cancelled'] as $status)<option value="{{ $status }}" @selected($order->status === $status)>{{ ucfirst($status) }}</option>@endforeach</select>
                                <select name="payment_status" style="margin: 0; min-width: 105px;">@foreach(['unpaid', 'partial', 'paid', 'refunded'] as $payment)<option value="{{ $payment }}" @selected($order->payment_status === $payment)>{{ ucfirst($payment) }}</option>@endforeach</select>
                                <button class="btn btn-primary" style="padding: 0.55rem;">Save</button>
                            </form>
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 2rem;">No orders recorded yet.</td></tr>
                @endforelse
            </tbody>
        </table>
        <div style="margin-top: 1.5rem;">{{ $orders->links() }}</div>
    </div>

    <div id="orderModal" style="display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.75); z-index: 1000; overflow-y: auto;">
        <div style="background: var(--card-bg); max-width: 760px; margin: 2rem auto; border-radius: 18px; padding: 2rem; position: relative;">
            <button type="button" onclick="document.getElementById('orderModal').style.display='none'" style="position: absolute; right: 1.5rem; top: 1.25rem; background: none; border: 0; color: white; font-size: 1.2rem;"><i class="fa-solid fa-xmark"></i></button>
            <h3 style="margin-bottom: 1.25rem;">Create Store Order / Bill</h3>
            <form method="POST" action="{{ route('vendor.orders.store') }}">
                @csrf
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div><label>Registered Customer</label><select name="customer_id"><option value="">Walk-in / Guest</option>@foreach($customers as $customer)<option value="{{ $customer->id }}">{{ $customer->name }} - {{ $customer->phone }}</option>@endforeach</select></div>
                    <div><label>Customer Name</label><input name="customer_name" placeholder="Walk-in customer name"></div>
                    <div><label>Phone</label><input name="customer_phone"></div>
                    <div><label>Email</label><input type="email" name="customer_email"></div>
                </div>
                <div id="orderItems">
                    <div class="order-item-row" style="display: grid; grid-template-columns: 2fr 0.65fr 0.8fr auto; gap: 0.75rem; align-items: end;">
                        <div><label>Product *</label><select name="items[0][product]" required><option value="">Select product</option><optgroup label="Frames">@foreach($frames as $frame)<option value="frame:{{ $frame->id }}">{{ $frame->name }} ({{ $frame->stock_quantity }} stock)</option>@endforeach</optgroup><optgroup label="Lenses">@foreach($lenses as $lens)<option value="lens:{{ $lens->id }}">{{ $lens->name }} ({{ $lens->stock_quantity }} stock)</option>@endforeach</optgroup></select></div>
                        <div><label>Qty *</label><input type="number" name="items[0][quantity]" min="1" value="1" required></div>
                        <div><label>Price</label><input type="number" name="items[0][unit_price]" min="0" step="0.01" placeholder="Catalog"></div>
                        <button type="button" class="btn btn-danger remove-item" style="margin-bottom: 1rem;"><i class="fa-solid fa-trash"></i></button>
                    </div>
                </div>
                <button type="button" id="addItem" class="btn" style="background: #334155; color: white; margin-bottom: 1rem;"><i class="fa-solid fa-plus"></i> Add Item</button>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div><label>Payment Status</label><select name="payment_status"><option value="unpaid">Unpaid</option><option value="partial">Partially Paid</option><option value="paid">Paid</option></select></div>
                    <div><label>Discount</label><input type="number" name="discount_amount" value="0" min="0" step="0.01"></div>
                </div>
                <label>Billing Address</label><textarea name="billing_address" rows="2"></textarea>
                <label>Notes</label><textarea name="notes" rows="2"></textarea>
                <button class="btn btn-primary" style="width: 100%; justify-content: center;">Create Order & Deduct Stock</button>
            </form>
        </div>
    </div>
    <script>
        const items = document.getElementById('orderItems');
        document.getElementById('addItem').addEventListener('click', () => {
            const row = items.querySelector('.order-item-row').cloneNode(true);
            const index = items.querySelectorAll('.order-item-row').length;
            row.querySelectorAll('select,input').forEach(field => {
                field.name = field.name.replace(/items\[\d+\]/, `items[${index}]`);
                if (field.tagName === 'SELECT') field.value = '';
                if (field.name.includes('quantity')) field.value = 1;
                if (field.name.includes('unit_price')) field.value = '';
            });
            items.appendChild(row);
        });
        items.addEventListener('click', event => {
            const button = event.target.closest('.remove-item');
            if (button && items.querySelectorAll('.order-item-row').length > 1) button.closest('.order-item-row').remove();
        });
    </script>
@endsection
