@extends('layouts.app')

@section('title', 'Novo Mercado')

@section('content')
<div class="sinagem-main">
    <div class="s-card">
        <div class="s-card-header">
            <h4 class="s-card-title">
                <i class="fas fa-plus-circle"></i>
                Novo Mercado
            </h4>
            <a href="{{ route('mercado.mercados.index') }}" class="btn btn-outline-secondary btn-sm">
                <i class="fas fa-arrow-left"></i>
                Voltar
            </a>
        </div>

        <div class="s-card-body">
            <form action="{{ route('mercado.mercados.store') }}" method="POST">
                @csrf

                <div class="row g-3">
                    <!-- Selecione Província -->
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="province_id" class="form-label">Província <span class="required">*</span></label>
                            <select id="province_id" class="form-control" required>
                                <option value="">Selecione a província...</option>
                                @foreach($provinces as $province)
                                    <option value="{{ $province->id }}">{{ $province->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <!-- Selecione Município -->
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="municipality_id" class="form-label">Município <span class="required">*</span></label>
                            <select id="municipality_id" class="form-control" disabled required>
                                <option value="">Primeiro selecione a província...</option>
                            </select>
                        </div>
                    </div>

                    <!-- Selecione Bairro -->
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="neighborhood_id" class="form-label">Bairro <span class="required">*</span></label>
                            <select name="neighborhood_id" id="neighborhood_id" class="form-control" disabled required>
                                <option value="">Primeiro selecione o município...</option>
                            </select>
                            @error('neighborhood_id')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name" class="form-label">Nome do Mercado <span class="required">*</span></label>
                            <input type="text"
                                   class="form-control @error('name') is-invalid @enderror"
                                   id="name"
                                   name="name"
                                   value="{{ old('name') }}"
                                   required>
                            @error('name')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="location" class="form-label">Localização <span class="required">*</span></label>
                            <input type="text"
                                   class="form-control @error('location') is-invalid @enderror"
                                   id="location"
                                   name="location"
                                   value="{{ old('location') }}"
                                   required>
                            @error('location')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="col-12">
                        <div class="form-group">
                            <label for="address" class="form-label">Endereço</label>
                            <textarea class="form-control @error('address') is-invalid @enderror"
                                      id="address"
                                      name="address"
                                      rows="2">{{ old('address') }}</textarea>
                            @error('address')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="capacity" class="form-label">Capacidade (nº bancadas)</label>
                            <input type="number"
                                   class="form-control @error('capacity') is-invalid @enderror"
                                   id="capacity"
                                   name="capacity"
                                   value="{{ old('capacity') }}"
                                   min="0">
                            @error('capacity')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="contact_phone" class="form-label">Telefone de Contacto</label>
                            <input type="text"
                                   class="form-control @error('contact_phone') is-invalid @enderror"
                                   id="contact_phone"
                                   name="contact_phone"
                                   value="{{ old('contact_phone') }}"
                                   placeholder="+244 923 456 789">
                            @error('contact_phone')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="contact_email" class="form-label">Email de Contacto</label>
                            <input type="email"
                                   class="form-control @error('contact_email') is-invalid @enderror"
                                   id="contact_email"
                                   name="contact_email"
                                   value="{{ old('contact_email') }}"
                                   placeholder="mercado@email.com">
                            @error('contact_email')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="status" class="form-label">Status</label>
                            <select name="status" id="status" class="form-control">
                                <option value="active" selected>Ativo</option>
                                <option value="inactive">Inativo</option>
                            </select>
                            @error('status')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="administration" class="form-label">Administração (JSON)</label>
                            <textarea class="form-control @error('administration') is-invalid @enderror"
                                      id="administration"
                                      name="administration"
                                      rows="2">{{ old('administration') }}</textarea>
                            <small class="form-hint">Informações adicionais sobre a administração do mercado</small>
                            @error('administration')
                                <div class="form-error">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>

                <div class="form-actions d-flex justify-content-end gap-2 mt-4">
                    <a href="{{ route('mercado.mercados.index') }}" class="btn btn-outline-secondary">
                        <i class="fas fa-times"></i>
                        Cancelar
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i>
                        Criar Mercado
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .required {
        color: var(--sinagem-red, #e03030);
    }

    .form-error {
        font-size: 0.75rem;
        color: var(--sinagem-red, #e03030);
        margin-top: 0.25rem;
    }

    .form-hint {
        font-size: 0.7rem;
        color: var(--text-muted, #9ca3af);
        margin-top: 0.25rem;
        display: block;
    }

    .form-actions {
        border-top: 1px solid var(--border-color, #e5e7eb);
        padding-top: 1.5rem;
    }
</style>
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const provinceSelect = document.getElementById('province_id');
    const municipalitySelect = document.getElementById('municipality_id');
    const neighborhoodSelect = document.getElementById('neighborhood_id');

    // URLs das rotas UTIL - Usando url() em vez de route() para evitar erro de parâmetro
    const municipalitiesUrl = '{{ url("util/municipalities") }}';
    const neighborhoodsUrl = '{{ url("util/neighborhoods") }}';

    async function loadMunicipalities(provinceId) {
        if (!provinceId) {
            municipalitySelect.innerHTML = '<option value="">Primeiro selecione a província...</option>';
            municipalitySelect.disabled = true;
            neighborhoodSelect.innerHTML = '<option value="">Primeiro selecione o município...</option>';
            neighborhoodSelect.disabled = true;
            return;
        }

        try {
            const response = await fetch(`${municipalitiesUrl}/${provinceId}`);
            const result = await response.json();

            if (result.success) {
                municipalitySelect.innerHTML = '<option value="">Selecione o município...</option>';
                result.data.forEach(municipality => {
                    municipalitySelect.innerHTML += `<option value="${municipality.id}">${municipality.name}</option>`;
                });
                municipalitySelect.disabled = false;
            } else {
                throw new Error(result.message || 'Erro ao carregar municípios');
            }
        } catch (error) {
            console.error('Erro ao carregar municípios:', error);
            municipalitySelect.innerHTML = '<option value="">Erro ao carregar municípios</option>';
        }
    }

    async function loadNeighborhoods(municipalityId) {
        if (!municipalityId) {
            neighborhoodSelect.innerHTML = '<option value="">Primeiro selecione o município...</option>';
            neighborhoodSelect.disabled = true;
            return;
        }

        try {
            const response = await fetch(`${neighborhoodsUrl}/${municipalityId}`);
            const result = await response.json();

            if (result.success) {
                neighborhoodSelect.innerHTML = '<option value="">Selecione o bairro...</option>';
                result.data.forEach(neighborhood => {
                    neighborhoodSelect.innerHTML += `<option value="${neighborhood.id}">${neighborhood.name}</option>`;
                });
                neighborhoodSelect.disabled = false;
            } else {
                throw new Error(result.message || 'Erro ao carregar bairros');
            }
        } catch (error) {
            console.error('Erro ao carregar bairros:', error);
            neighborhoodSelect.innerHTML = '<option value="">Erro ao carregar bairros</option>';
        }
    }

    provinceSelect.addEventListener('change', (e) => loadMunicipalities(e.target.value));
    municipalitySelect.addEventListener('change', (e) => loadNeighborhoods(e.target.value));
});
</script>
@endpush
