@extends('layouts.app')

@section('content')
    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <h4 class="mb-0">Trade fairs</h4>
        <a href="{{ route('tradefairs.create') }}" class="btn btn-success">Add trade fair</a>
    </div>

    <div class="card shadow-sm mb-3">
        <div class="card-header fw-bold">Filter</div>
        <div class="card-body">
            <form method="GET" action="{{ route('tradefairs.index') }}" class="row g-2 align-items-end">
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-0">Continent</label>
                    <select name="f_continent_id" id="filter_continent" class="form-select form-select-sm">
                        <option value="">All continents</option>
                        @foreach($continents as $c)
                            <option value="{{ $c->id }}" {{ (string) request('f_continent_id') === (string) $c->id ? 'selected' : '' }}>{{ $c->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-0">Country</label>
                    <select name="f_country_id" id="filter_country" class="form-select form-select-sm">
                        <option value="">All countries</option>
                        @foreach($filterCountries as $c)
                            <option value="{{ $c->id }}" {{ (string) request('f_country_id') === (string) $c->id ? 'selected' : '' }}>{{ $c->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small text-muted mb-0">City</label>
                    <select name="f_city_id" id="filter_city" class="form-select form-select-sm">
                        <option value="">All cities</option>
                        @foreach($filterCities as $ct)
                            <option value="{{ $ct->id }}" {{ (string) request('f_city_id') === (string) $ct->id ? 'selected' : '' }}>{{ $ct->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 d-flex gap-2">
                    <button type="submit" class="btn btn-primary btn-sm">Apply</button>
                    <a href="{{ route('tradefairs.index') }}" class="btn btn-outline-secondary btn-sm">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="card-header fw-bold d-flex justify-content-between align-items-center">
            <span>Listing ({{ $tradefairs->count() }})</span>
        </div>
        <div class="card-body p-0 table-responsive">
            <table class="table table-sm table-hover mb-0 align-middle">
                <thead>
                <tr>
                    <th>Fair Name</th>
                    <th>Continent</th>
                    <th>Country</th>
                    <th>City</th>
                    <th>Start</th>
                    <th>End</th>
                    <th class="text-end">Actions</th>
                </tr>
                </thead>
                <tbody>
                @forelse($tradefairs as $tf)
                    <tr>
                        <td>{{ $tf->fair_name }}</td>
                        <td>{{ optional($tf->fairContinent)->name ?: $tf->contient ?: '—' }}</td>
                        <td>{{ optional($tf->fairCountry)->name ?: $tf->country ?: '—' }}</td>
                        <td>{{ $tf->eventvenue ?: '—' }}</td>
                        <td class="small">{{ optional($tf->event_start_date)->format('Y-m-d') ?: '—' }}</td>
                        <td class="small">{{ optional($tf->event_end_date)->format('Y-m-d') ?: '—' }}</td>
                        <td class="text-end text-nowrap">
                            <a href="{{ route('tradefairs.edit', $tf) }}" class="btn btn-sm btn-outline-secondary">Edit</a>
                            <form method="POST" action="{{ route('tradefairs.destroy', $tf) }}" class="d-inline" onsubmit="return confirm('Delete this trade fair?');">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
                            </form>
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="7" class="text-center text-muted py-4">No trade fairs match the filters.</td></tr>
                @endforelse
                </tbody>
            </table>
        </div>
    </div>
@endsection

@push('scripts')
<script>
(function () {
    var countriesUrl = @json(route('locations.countries-by-continent'));
    var citiesUrl = @json(route('locations.cities-by-country'));

    function fillSelect(select, items, placeholder, selectedId) {
        select.innerHTML = '';
        var p = document.createElement('option');
        p.value = '';
        p.textContent = placeholder;
        select.appendChild(p);
        (items || []).forEach(function (row) {
            var o = document.createElement('option');
            o.value = row.id;
            o.textContent = row.name;
            if (selectedId && String(row.id) === String(selectedId)) o.selected = true;
            select.appendChild(o);
        });
    }

    function loadCountries(continentId, target, citySelect) {
        if (!continentId) {
            target.disabled = true;
            fillSelect(target, [], '— Select continent first —', null);
            if (citySelect) {
                citySelect.disabled = true;
                fillSelect(citySelect, [], '— Select country first —', null);
            }
            return;
        }
        target.disabled = true;
        fetch(countriesUrl + '?continent_id=' + encodeURIComponent(continentId), {
            headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function (r) { return r.json(); }).then(function (rows) {
            target.disabled = false;
            fillSelect(target, rows, '— Select country —', null);
            if (citySelect) {
                citySelect.disabled = true;
                fillSelect(citySelect, [], '— Select country first —', null);
            }
        });
    }

    function loadCities(countryId, target) {
        if (!countryId) {
            target.disabled = true;
            fillSelect(target, [], '— Select country first —', null);
            return;
        }
        target.disabled = true;
        fetch(citiesUrl + '?country_id=' + encodeURIComponent(countryId), {
            headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function (r) { return r.json(); }).then(function (rows) {
            target.disabled = false;
            fillSelect(target, rows, '— Select city —', null);
        });
    }

    var fC = document.getElementById('filter_continent');
    var fCo = document.getElementById('filter_country');
    var fCi = document.getElementById('filter_city');
    if (fC && fCo) {
        fC.addEventListener('change', function () {
            loadCountries(this.value, fCo, fCi);
        });
    }
    if (fCo && fCi) {
        fCo.addEventListener('change', function () {
            loadCities(this.value, fCi);
        });
    }
})();
</script>
@endpush
