@extends('adminlte::page')

@section('content')
<div class="container">
    <h2>Vendors</h2>
    <a href="{{ route('vendors.create') }}" class="btn btn-primary mb-3">Add Vendor</a>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th></th>
                <th>Company Name</th>
                <th>Category</th>
                <th>Phone</th>
                <th>Email</th>
                <th>TRN</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach($vendors as $vendor)
            <tr>
                <td>
                    @if($vendor->contacts->count())
                        <button class="btn btn-sm btn-link toggle-contacts" data-id="{{ $vendor->id }}">+</button>
                    @endif
                </td>
                <td>{{ $vendor->company_name }}</td>
                <td>{{ $vendor->category }}</td>
                <td>{{ $vendor->phone }}</td>
                <td>{{ $vendor->email }}</td>
                <td>{{ $vendor->trn }}</td>
                <td>
                    <a href="{{ route('vendors.edit', $vendor) }}" class="btn btn-sm btn-warning">Edit</a>
                </td>
            </tr>
            @if($vendor->contacts->count())
            <tr id="contacts-{{ $vendor->id }}" class="contacts-row" style="display: none;">
                <td colspan="7">
                    <strong>Contacts:</strong>
                    <ul>
                        @foreach($vendor->contacts as $contact)
                            <li>
                                <strong>{{ $contact->name }}</strong> ({{ $contact->designation ?? 'N/A' }})
                                — Mobile: {{ $contact->mobile1 }}
                                @if($contact->mobile2) / {{ $contact->mobile2 }} @endif
                                @if($contact->mobile3) / {{ $contact->mobile3 }} @endif
                                — Email: {{ $contact->email }}
                            </li>
                        @endforeach
                    </ul>
                </td>
            </tr>
            @endif
            @endforeach
        </tbody>
    </table>
</div>

@push('scripts')
<script>
    document.querySelectorAll('.toggle-contacts').forEach(btn => {
        btn.addEventListener('click', function () {
            const id = this.dataset.id;
            const row = document.getElementById(`contacts-${id}`);
            row.style.display = row.style.display === 'none' ? 'table-row' : 'none';
            this.textContent = this.textContent === '+' ? '−' : '+';
        });
    });
</script>
@endpush
@endsection
