@extends('layouts.admin')
@section('title', 'Vendors & Suppliers')
@section('page-title', 'Vendors / Suppliers')

@section('content')
<div class="billing-clients-page billing-vendors-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-vendor-filters" aria-expanded="{{ $hasFilters ? 'true' : 'false' }}">
                            <i class="ri-filter-3-line me-1"></i> Filter Vendors / Suppliers
                            @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.vendors.index') }}" class="billing-invoice-quick-search">
                            @foreach(collect($filters)->except('q') as $key => $val)
                                @if($val)<input type="hidden" name="{{ $key }}" value="{{ $val }}">@endif
                            @endforeach
                            <input type="hidden" name="sort" value="{{ $sortBy }}">
                            <input type="hidden" name="dir" value="{{ $sortDir }}">
                            <i class="ri-search-line"></i>
                            <input type="text" name="q" class="form-control" placeholder="Search vendor, code, GSTIN..." value="{{ $filters['q'] ?? '' }}">
                        </form>
                    </div>
                    <div class="col-lg-auto d-flex gap-2 align-items-center">
                        <div class="dropdown">
                            <button type="button" class="btn btn-light border dropdown-toggle" data-bs-toggle="dropdown" title="Sort list">
                                <i class="ri-sort-desc me-1"></i> Sort
                            </button>
                            <div class="dropdown-menu dropdown-menu-end billing-sort-dropdown shadow p-0">
                                @include('admin.vendors.partials.sort-menu', ['sortOptions' => $sortOptionsTable])
                            </div>
                        </div>
                        <a href="{{ route('admin.vendors.create') }}" class="btn btn-success"><i class="ri-add-line me-1"></i> New</a>
                        <a href="{{ route('admin.vendors.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="vendor-filters">
            <div class="card border-0 shadow-sm mb-3 billing-invoice-filters">
                <div class="card-body">
                    <form method="GET" action="{{ route('admin.vendors.index') }}">
                        <input type="hidden" name="sort" value="{{ $sortBy }}">
                        <input type="hidden" name="dir" value="{{ $sortDir }}">
                        <div class="row g-3">
                            <div class="col-md-3"><label class="form-label">Company name</label><input type="text" name="company_name" class="form-control" value="{{ $filters['company_name'] ?? '' }}"></div>
                            <div class="col-md-3"><label class="form-label">Contact name</label><input type="text" name="contact_name" class="form-control" value="{{ $filters['contact_name'] ?? '' }}"></div>
                            <div class="col-md-3"><label class="form-label">Email</label><input type="text" name="email" class="form-control" value="{{ $filters['email'] ?? '' }}"></div>
                            <div class="col-md-3"><label class="form-label">Phone</label><input type="text" name="phone" class="form-control" value="{{ $filters['phone'] ?? '' }}"></div>
                            <div class="col-md-3"><label class="form-label">Vendor code</label><input type="text" name="vendor_code" class="form-control" value="{{ $filters['vendor_code'] ?? '' }}"></div>
                            <div class="col-md-3">
                                <label class="form-label">State</label>
                                <select name="state" class="form-select">
                                    <option value="">All</option>
                                    @foreach($states as $st)
                                        <option value="{{ $st }}" @selected(($filters['state'] ?? '') === $st)>{{ $st }}</option>
                                    @endforeach
                                </select>
                            </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.vendors.index') }}" class="btn btn-light">Clear</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="card billing-page-card border-0 shadow-sm">
            @if($vendors->isNotEmpty())
                <div class="billing-table-wrap table-responsive">
                    <table class="table table-hover align-middle mb-0 billing-clients-table">
                        <thead>
                            <tr>
                                <th style="width:36px"><input type="checkbox" class="form-check-input" id="check-all-vendors"></th>
                                @php
                                    $thSort = fn ($col) => route('admin.vendors.index', array_merge(request()->query(), [
                                        'sort' => $col,
                                        'dir' => ($sortBy === $col && $sortDir === 'asc') ? 'desc' : 'asc',
                                    ]));
                                @endphp
                                <th>
                                    <a href="{{ $thSort('name') }}" class="billing-th-sort {{ $sortBy === 'name' ? 'is-active' : '' }}">
                                        Company name <i class="ri-arrow-{{ $sortBy === 'name' && $sortDir === 'desc' ? 'down' : 'up' }}-s-line"></i>
                                    </a>
                                </th>
                                <th>Contact name</th>
                                <th>
                                    <a href="{{ $thSort('balance') }}" class="billing-th-sort {{ $sortBy === 'balance' ? 'is-active' : '' }}">
                                        Balance <i class="ri-arrow-{{ $sortBy === 'balance' && $sortDir === 'desc' ? 'down' : 'up' }}-s-line"></i>
                                    </a>
                                </th>
                                <th>Billing address</th>
                                <th>
                                    <a href="{{ $thSort('state') }}" class="billing-th-sort {{ $sortBy === 'state' ? 'is-active' : '' }}">
                                        State <i class="ri-arrow-{{ $sortBy === 'state' && $sortDir === 'desc' ? 'down' : 'up' }}-s-line"></i>
                                    </a>
                                </th>
                                <th>
                                    <a href="{{ $thSort('email') }}" class="billing-th-sort {{ $sortBy === 'email' ? 'is-active' : '' }}">
                                        Email <i class="ri-arrow-{{ $sortBy === 'email' && $sortDir === 'desc' ? 'down' : 'up' }}-s-line"></i>
                                    </a>
                                </th>
                                <th>Phone</th>
                                <th>Code</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($vendors as $vendor)
                                <tr>
                                    <td><input type="checkbox" class="form-check-input vendor-check" value="{{ $vendor->id }}"></td>
                                    <td>
                                        <a href="{{ route('admin.vendors.index', array_merge(request()->query(), ['vendor' => $vendor->id])) }}" class="billing-client-link fw-medium">
                                            {{ $vendor->name }}
                                        </a>
                                    </td>
                                    <td>{{ $vendor->contact_person ?? '—' }}</td>
                                    <td class="fw-medium">₹{{ number_format($vendor->currentBalance(), 2) }}</td>
                                    <td class="text-muted small">{{ $vendor->billingAddressShort() }}</td>
                                    <td>{{ $vendor->state ?? '—' }}</td>
                                    <td>{{ $vendor->email ?? '—' }}</td>
                                    <td>{{ $vendor->phone ?? '—' }}</td>
                                    <td>{{ $vendor->vendor_code ?? '—' }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <div class="card-body">
                    @include('admin.vendors.partials.empty')
                </div>
            @endif
        </div>
    @else
        <div class="billing-clients-split row g-0">
            <div class="col-lg-4 col-xl-3 billing-clients-sidebar">
                @include('admin.vendors.partials.sidebar-toolbar')

                <div class="billing-clients-sidebar__search px-2 pb-2">
                    <form method="GET" action="{{ route('admin.vendors.index') }}" class="billing-sidebar-search">
                        @foreach(request()->only(['vendor', 'view', 'from', 'to', 'txn', 'sort', 'dir', 'company_name', 'contact_name', 'email', 'phone', 'state', 'vendor_code', 'q']) as $key => $val)
                            @if($val)<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="Quick search..." value="{{ $filters['q'] ?? '' }}">
                    </form>
                </div>

                <div class="billing-clients-sidebar__list">
                    @forelse($vendors as $vendor)
                        <a href="{{ route('admin.vendors.index', array_merge(
                                request()->only(['view', 'from', 'to', 'txn', 'q', 'sort', 'dir', 'company_name', 'contact_name', 'email', 'phone', 'state', 'vendor_code']),
                                ['vendor' => $vendor->id]
                            )) }}"
                           class="billing-client-list-item {{ $selected && $selected->id === $vendor->id ? 'is-active' : '' }}">
                            <div class="billing-client-list-item__avatar billing-client-list-item__avatar--vendor">{{ strtoupper(substr($vendor->name, 0, 1)) }}</div>
                            <div class="billing-client-list-item__content">
                                <div class="billing-client-list-item__name">{{ $vendor->name }}</div>
                                <div class="billing-client-list-item__sub">{{ $vendor->contact_person ?? $vendor->email ?? '—' }}</div>
                            </div>
                            <div class="billing-client-list-item__balance">₹{{ number_format($vendor->currentBalance(), 2) }}</div>
                        </a>
                    @empty
                        <div class="p-3 text-muted small">No vendors match filters.</div>
                    @endforelse
                </div>
            </div>

            <div class="col-lg-8 col-xl-9 billing-clients-panel">
                @if($selected)
                    <div class="billing-clients-panel__toolbar">
                        <a href="{{ route('admin.vendors.edit', $selected) }}" class="btn btn-panel-action"><i class="ri-pencil-line"></i><span>Edit</span></a>
                        @if($view === 'statement')
                            <div class="dropdown">
                                <button type="button" class="btn btn-panel-action dropdown-toggle" data-bs-toggle="dropdown">
                                    <i class="ri-filter-3-line"></i><span>Filter</span>
                                </button>
                                <div class="dropdown-menu dropdown-menu-end p-3 billing-statement-filter-menu shadow" style="min-width:320px">
                                    @include('admin.vendors.partials.statement-filter-form')
                                </div>
                            </div>
                            <button type="button" class="btn btn-panel-action" onclick="window.print()"><i class="ri-file-pdf-line"></i><span>PDF</span></button>
                            <button type="button" class="btn btn-panel-action" onclick="window.print()"><i class="ri-printer-line"></i><span>Print</span></button>
                        @else
                            <a href="{{ route('admin.vendors.index', array_merge(request()->only(['sort', 'dir', 'q']), ['vendor' => $selected->id, 'view' => 'statement', 'from' => $statementFrom, 'to' => $statementTo])) }}" class="btn btn-panel-action">
                                <i class="ri-file-chart-line"></i><span>Statement</span>
                            </a>
                        @endif
                        <div class="dropdown ms-auto">
                            <button type="button" class="btn btn-panel-action dropdown-toggle" data-bs-toggle="dropdown"><i class="ri-more-2-line"></i><span>More</span></button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="{{ route('admin.purchase-bills.create') }}"><i class="ri-file-list-3-line me-2"></i>New Purchase Bill</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li>
                                    <form action="{{ route('admin.vendors.destroy', $selected) }}" method="POST" onsubmit="return confirm('Delete this vendor?')">
                                        @csrf @method('DELETE')
                                        <button type="submit" class="dropdown-item text-danger"><i class="ri-delete-bin-line me-2"></i>Delete</button>
                                    </form>
                                </li>
                            </ul>
                        </div>
                        <a href="{{ route('admin.vendors.index', request()->only(['sort', 'dir', 'q', 'company_name', 'contact_name', 'email', 'phone', 'state', 'vendor_code'])) }}" class="btn btn-panel-close" title="Close detail"><i class="ri-close-line"></i></a>
                    </div>

                    <div class="billing-clients-panel__body">
                        @if($view === 'statement' && $statement)
                            @include('admin.vendors.partials.statement')
                        @else
                            @include('admin.vendors.partials.detail')
                        @endif
                    </div>
                @endif
            </div>
        </div>
    @endif
</div>
@endsection

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

    const checkAll = document.getElementById('check-all-vendors');
    if (checkAll) {
        checkAll.addEventListener('change', function () {
            document.querySelectorAll('.vendor-check').forEach(cb => cb.checked = this.checked);
        });
    }
});
</script>
@endpush
