@extends('layouts.admin')
@section('title', 'Purchase Orders')
@section('page-title', 'Purchase Orders')

@section('content')
<div class="billing-invoices-page billing-quotes-page billing-clients-page">
    @if(!$panelOpen)
    <div class="billing-invoice-toolbar card border-0 shadow-sm mb-3">
        <div class="card-body py-3">
            <div class="row g-2 align-items-center">
                <div class="col-lg-auto">
                    <button type="button" class="btn btn-dark" id="btn-toggle-filters" aria-expanded="{{ $hasFilters ? 'true' : 'false' }}">
                        <i class="ri-filter-3-line me-1"></i> Filter Purchase Orders
                        @if($hasFilters)<span class="badge bg-light text-dark ms-1">!</span>@endif
                    </button>
                </div>
                <div class="col-lg flex-grow-1">
                    <form method="GET" action="{{ route('admin.purchase-orders.index') }}" class="billing-invoice-quick-search" id="quick-search-form">
                        @foreach(collect($filters)->except('q') as $key => $val)
                            @if($val && $val !== 'all')
                                <input type="hidden" name="{{ $key }}" value="{{ $val }}">
                            @endif
                        @endforeach
                        <i class="ri-search-line"></i>
                        <input type="text" name="q" class="form-control" placeholder="Search purchase orders, vendors..." value="{{ $filters['q'] ?? '' }}">
                    </form>
                </div>
                <div class="col-lg-auto d-flex gap-2">
                    <div class="dropdown">
                        <button type="button" class="btn btn-success dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="ri-add-line me-1"></i> New
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end billing-invoice-new-menu shadow">
                            <li>
                                <a class="dropdown-item py-2" href="{{ route('admin.purchase-orders.create') }}">
                                    <i class="ri-file-reduce-line me-2 text-success"></i>
                                    <span class="d-block fw-medium">Purchase Order</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                    <a href="{{ route('admin.purchase-orders.export', request()->query()) }}" class="btn btn-light border">
                        <i class="ri-download-2-line me-1"></i> Export
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="collapse {{ $hasFilters ? 'show' : '' }}" id="purchase-order-filters">
        <div class="card border-0 shadow-sm mb-3 billing-invoice-filters">
            <div class="card-body">
                <form method="GET" action="{{ route('admin.purchase-orders.index') }}">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">Vendor name</label>
                            <input type="text" name="vendor_name" class="form-control" value="{{ $filters['vendor_name'] ?? '' }}" placeholder="Search vendor">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Doc. no</label>
                            <input type="text" name="purchase_order_number" class="form-control" value="{{ $filters['purchase_order_number'] ?? '' }}" placeholder="PO number">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="all">All</option>
                                @foreach($statuses as $key => $meta)
                                    <option value="{{ $key }}" @selected(($filters['status'] ?? 'all') === $key)>{{ $meta['label'] }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Issued between</label>
                            <div class="input-group">
                                <input type="date" name="issued_from" class="form-control" value="{{ $filters['issued_from'] ?? '' }}">
                                <span class="input-group-text">to</span>
                                <input type="date" name="issued_to" class="form-control" value="{{ $filters['issued_to'] ?? '' }}">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">City</label>
                            <input type="text" name="city" class="form-control" value="{{ $filters['city'] ?? '' }}" placeholder="Vendor city">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Amount between</label>
                            <div class="input-group">
                                <input type="number" step="0.01" name="amount_min" class="form-control" value="{{ $filters['amount_min'] ?? '' }}" placeholder="Min">
                                <span class="input-group-text">and</span>
                                <input type="number" step="0.01" name="amount_max" class="form-control" value="{{ $filters['amount_max'] ?? '' }}" placeholder="Max">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Item name</label>
                            <input type="text" name="item_name" class="form-control" value="{{ $filters['item_name'] ?? '' }}" placeholder="Line item name">
                        </div>
                    </div>
                    <div class="d-flex gap-2 mt-3">
                        <button type="submit" class="btn btn-success px-4">Apply</button>
                        <a href="{{ route('admin.purchase-orders.index') }}" class="btn btn-light">Clear</a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="card billing-page-card border-0 shadow-sm">
        @if($purchaseOrders->isNotEmpty())
            <div class="billing-table-wrap table-responsive">
                <table class="table table-hover align-middle mb-0 billing-invoice-table">
                    <thead>
                        <tr>
                            <th style="width:36px"><input type="checkbox" class="form-check-input" id="check-all"></th>
                            <th>Issue Date <i class="ri-arrow-up-down-line text-muted fs-12"></i></th>
                            <th>Doc. No. <i class="ri-arrow-up-down-line text-muted fs-12"></i></th>
                            <th>Status</th>
                            <th>Vendor Name <i class="ri-arrow-up-down-line text-muted fs-12"></i></th>
                            <th>Valid Until <i class="ri-arrow-up-down-line text-muted fs-12"></i></th>
                            <th class="text-end">Amount <i class="ri-arrow-up-down-line text-muted fs-12"></i></th>
                            <th class="text-end" style="width:80px">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($purchaseOrders as $note)
                            @php $status = $note->statusMeta(); @endphp
                            <tr>
                                <td><input type="checkbox" class="form-check-input purchase-order-check" value="{{ $note->id }}"></td>
                                <td>
                                    <a href="{{ route('admin.purchase-orders.index', array_merge(request()->query(), ['purchase_order' => $note->id])) }}" class="billing-client-link text-body">
                                        {{ $note->po_date->format('d M Y') }}
                                    </a>
                                </td>
                                <td>
                                    <a href="{{ route('admin.purchase-orders.index', array_merge(request()->query(), ['purchase_order' => $note->id])) }}" class="billing-client-link fw-medium">
                                        {{ $note->purchase_order_number }}
                                    </a>
                                </td>
                                <td>
                                    <span class="badge bg-{{ $status['color'] }}-subtle text-{{ $status['color'] }}">
                                        {{ $status['label'] }}
                                    </span>
                                </td>
                                <td>
                                    <a href="{{ route('admin.purchase-orders.index', array_merge(request()->query(), ['purchase_order' => $note->id])) }}" class="billing-client-link text-body">
                                        {{ $note->partyName() }}
                                    </a>
                                </td>
                                <td>{{ $note->valid_until?->format('d M Y') ?? '—' }}</td>
                                <td class="text-end fw-medium">₹{{ number_format($note->grand_total, 2) }}</td>
                                <td class="text-end">
                                    <div class="d-flex gap-1 justify-content-end">
                                        <a href="{{ route('admin.purchase-orders.index', array_merge(request()->query(), ['purchase_order' => $note->id])) }}" class="btn btn-sm btn-soft-info" title="View"><i class="ri-eye-line"></i></a>
                                        <a href="{{ route('admin.purchase-orders.edit', $note) }}" class="btn btn-sm btn-soft-primary" title="Edit"><i class="ri-pencil-line"></i></a>
                                        <form action="{{ route('admin.purchase-orders.destroy', $note) }}" method="POST" class="d-inline" onsubmit="return confirm('Delete this purchase order?')">
                                            @csrf @method('DELETE')
                                            <button type="submit" class="btn btn-sm btn-soft-danger" title="Delete"><i class="ri-delete-bin-line"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @else
            <div class="card-body">
                <div class="billing-invoice-empty text-center py-4">
                    <h4 class="fw-semibold mb-2">There are no purchase orders created yet</h4>
                    <p class="text-muted mx-auto mb-4" style="max-width:520px">
                        Create purchase orders for your vendors with line items, GST, validity dates, and PDF sharing.
                    </p>
                    <a href="{{ route('admin.purchase-orders.create') }}" class="btn btn-primary btn-lg px-4 mb-5">
                        <i class="ri-add-line me-1"></i> New Purchase Order
                    </a>

                    @include('admin.purchase-orders.partials.lifecycle')

                    <h6 class="text-start fw-semibold mt-4 mb-3">In the Purchase Orders tab, you can:</h6>
                    <div class="billing-invoice-features row g-3 text-start">
                        @foreach(config('purchase_order.empty_state.capabilities', $features) as $feature)
                            <div class="col-md-12">
                                <div class="d-flex gap-2">
                                    <i class="ri-checkbox-circle-fill text-success fs-18 flex-shrink-0"></i>
                                    <span class="text-muted">{{ $feature }}</span>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        @endif
    </div>

    @if($purchaseOrders->isNotEmpty())
        <div class="mt-4">
            @include('admin.purchase-orders.partials.lifecycle')
        </div>
    @endif
    @else
        <div class="billing-clients-split row g-0">
            <div class="col-lg-4 col-xl-3 billing-clients-sidebar">
                @include('admin.purchase-orders.partials.sidebar-toolbar')

                <div class="billing-clients-sidebar__search px-2 pb-2">
                    <form method="GET" action="{{ route('admin.purchase-orders.index') }}" class="billing-sidebar-search">
                        @foreach(request()->only([
                            'purchase_order', 'q', 'vendor_name', 'purchase_order_number', 'status',
                            'issued_from', 'issued_to', 'amount_min', 'amount_max', 'city', 'item_name',
                        ]) as $key => $val)
                            @if($val && $val !== 'all')<input type="hidden" name="{{ $key }}" value="{{ $val }}">@endif
                        @endforeach
                        <i class="ri-search-line"></i>
                        <input type="text" name="q" class="form-control form-control-sm" placeholder="Search purchase orders..." value="{{ $filters['q'] ?? '' }}">
                    </form>
                </div>

                <div class="billing-clients-sidebar__list">
                    @forelse($purchaseOrders as $note)
                        @php $qStatus = $note->statusMeta(); @endphp
                        <a href="{{ route('admin.purchase-orders.index', array_merge(
                                request()->only([
                                    'q', 'vendor_name', 'purchase_order_number', 'status',
                                    'issued_from', 'issued_to', 'amount_min', 'amount_max', 'city', 'item_name',
                                ]),
                                ['purchase_order' => $note->id]
                            )) }}"
                           class="billing-client-list-item {{ $selected && $selected->id === $note->id ? 'is-active' : '' }}">
                            <div class="billing-client-list-item__avatar billing-client-list-item__avatar--invoice">
                                <i class="ri-file-copy-2-line"></i>
                            </div>
                            <div class="billing-client-list-item__content">
                                <div class="billing-client-list-item__name">{{ $note->purchase_order_number }}</div>
                                <div class="billing-client-list-item__sub">{{ $note->partyName() }} · {{ $note->po_date->format('d M Y') }}</div>
                            </div>
                            <div class="billing-client-list-item__balance text-end">
                                <div>₹{{ number_format($note->grand_total, 2) }}</div>
                                <span class="badge bg-{{ $qStatus['color'] }}-subtle text-{{ $qStatus['color'] }} mt-1" style="font-size:0.65rem">{{ $qStatus['label'] }}</span>
                            </div>
                        </a>
                    @empty
                        <div class="p-3 text-muted small">No purchase orders match filters.</div>
                    @endforelse
                </div>
            </div>

            <div class="col-lg-8 col-xl-9 billing-clients-panel">
                @if($selected && isset($purchaseOrder))
                    <div class="billing-clients-panel__body billing-clients-panel__body--invoice-preview p-0">
                        @include('admin.purchase-orders.partials.preview', [
                            'embedded' => true,
                            'closeUrl' => route('admin.purchase-orders.index', request()->except('purchase_order')),
                        ])
                    </div>
                @endif
            </div>
        </div>
    @endif
</div>
@endsection

@push('styles')
@if($panelOpen ?? false)
<link href="{{ asset('css/billing-invoice-preview.css') }}" rel="stylesheet">
<link href="{{ asset('css/billing-invoice-document.css') }}" rel="stylesheet">
<link href="{{ asset('css/billing-invoice-print.css') }}" rel="stylesheet">
@endif
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const filterBtn = document.getElementById('btn-toggle-filters');
    const filterPanel = document.getElementById('purchase-order-filters');
    if (filterBtn && filterPanel) {
        filterBtn.addEventListener('click', function () {
            const collapse = bootstrap.Collapse.getOrCreateInstance(filterPanel);
            collapse.toggle();
        });
    }

    const checkAll = document.getElementById('check-all');
    if (checkAll) {
        checkAll.addEventListener('change', function () {
            document.querySelectorAll('.purchase-order-check').forEach(cb => cb.checked = this.checked);
        });
    }
});
</script>
@if($panelOpen ?? false)
@include('admin.purchase-orders.partials.preview-scripts')
@endif
@endpush
