@extends('layouts.app')

@section('title', 'Mercados')

@section('content')
<div class="sinagem-main">
    <div class="s-card">
        <div class="s-card-header">
            <h4 class="s-card-title">
                <i class="fas fa-store"></i>
                Mercados
            </h4>
            <a href="{{ route('mercado.mercados.create') }}" class="btn btn-primary btn-sm">
                <i class="fas fa-plus-circle"></i>
                Novo Mercado
            </a>
        </div>

        <div class="s-card-body">
            @if(session('success'))
                <div class="sinagem-alert sinagem-alert-success">
                    <i class="fas fa-check-circle"></i>
                    <span>{{ session('success') }}</span>
                    <button type="button" class="flash-close">&times;</button>
                </div>
            @endif

            @if(session('error'))
                <div class="sinagem-alert sinagem-alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <span>{{ session('error') }}</span>
                    <button type="button" class="flash-close">&times;</button>
                </div>
            @endif

            <!-- Filtros -->
            <form method="GET" class="row g-3 mb-4 align-items-end">
                <div class="col-md-3">
                    <label for="province_id" class="form-label">Província</label>
                    <select name="province_id" id="province_id" class="form-control">
                        <option value="">Todas</option>
                        @foreach($provinces ?? [] as $province)
                            <option value="{{ $province->id }}" {{ request('province_id') == $province->id ? 'selected' : '' }}>
                                {{ $province->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="municipality_id" class="form-label">Município</label>
                    <select name="municipality_id" id="municipality_id" class="form-control">
                        <option value="">Todos</option>
                        @foreach($municipalities ?? [] as $municipality)
                            <option value="{{ $municipality->id }}" {{ request('municipality_id') == $municipality->id ? 'selected' : '' }}>
                                {{ $municipality->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="status" class="form-label">Status</label>
                    <select name="status" id="status" class="form-control">
                        <option value="">Todos</option>
                        <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Ativo</option>
                        <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Inativo</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="search" class="form-label">Pesquisar</label>
                    <input type="text" name="search" id="search" class="form-control" placeholder="Nome, localização..." value="{{ request('search') }}">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search"></i> Filtrar
                    </button>
                </div>
            </form>

            <!-- Tabela DataTable -->
            <div class="sinagem-datatable-wrapper">
                <div class="table-responsive">
                    <table id="mercados-table" class="s-table">
                        <thead>
                            <tr>
                                <th>Nome</th>
                                <th>Localização</th>
                                <th>Província</th>
                                <th>Município</th>
                                <th>Status</th>
                                <th>Capacidade</th>
                                <th>Ocupação</th>
                                <th class="text-center">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- DataTables preenche via AJAX -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .sinagem-alert {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.75rem 1rem;
        border-radius: var(--radius-md, 8px);
        margin-bottom: 1rem;
        border-left: 3px solid;
    }

    .sinagem-alert-success {
        background: #d1fae5;
        border-left-color: #10b981;
        color: #065f46;
    }

    .sinagem-alert-danger {
        background: #fee2e2;
        border-left-color: #ef4444;
        color: #991b1b;
    }

    .flash-close {
        margin-left: auto;
        background: none;
        border: none;
        font-size: 1.1rem;
        cursor: pointer;
        color: inherit;
        opacity: 0.6;
    }

    .flash-close:hover {
        opacity: 1;
    }

    .btn-action.btn-info {
        color: #3b82f6;
        background: rgba(59, 130, 246, 0.1);
    }

    .btn-action.btn-info:hover {
        background: #3b82f6;
        color: white;
        transform: translateY(-2px);
    }
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    const table = $('#mercados-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ route("mercado.mercados.table-data") }}',
            type: 'GET',
            data: function(d) {
                d.province_id = $('#province_id').val();
                d.municipality_id = $('#municipality_id').val();
                d.status = $('#status').val();
                d.search = $('#search').val();
            }
        },
        columns: [
            { data: 'name', name: 'name' },
            { data: 'location', name: 'location' },
            { data: 'province', name: 'province' },
            { data: 'municipality', name: 'municipality' },
            { data: 'status', name: 'status' },
            { data: 'capacity', name: 'capacity' },
            { data: 'occupation_rate', name: 'occupation_rate' },
            { data: 'actions', name: 'actions', orderable: false, searchable: false, className: 'text-center' }
        ],
        pageLength: 15,
        language: {
            processing: '<i class="fas fa-spinner fa-spin"></i> Processando...',
            search: '<i class="fas fa-search"></i> Pesquisar:',
            lengthMenu: 'Mostrar _MENU_ registros por página',
            info: 'Mostrando _START_ a _END_ de _TOTAL_ registros',
            infoEmpty: 'Mostrando 0 a 0 de 0 registros',
            infoFiltered: '(filtrado de _MAX_ registros no total)',
            loadingRecords: '<i class="fas fa-spinner fa-spin"></i> Carregando...',
            zeroRecords: '<i class="fas fa-database"></i> Nenhum registro encontrado',
            emptyTable: '<i class="fas fa-table"></i> Nenhum dado disponível na tabela',
            paginate: {
                first: '<i class="fas fa-angle-double-left"></i>',
                previous: '<i class="fas fa-angle-left"></i>',
                next: '<i class="fas fa-angle-right"></i>',
                last: '<i class="fas fa-angle-double-right"></i>'
            }
        },
        responsive: true,
        order: [[0, 'asc']],
        drawCallback: function() {
            initTooltips();
        }
    });

    $('#province_id, #municipality_id, #status, #search').on('change keyup', function() {
        table.ajax.reload();
    });

    function initTooltips() {
        if (typeof bootstrap !== 'undefined') {
            $('[title]').each(function() {
                const tooltip = bootstrap.Tooltip.getInstance(this);
                if (tooltip) tooltip.dispose();
                new bootstrap.Tooltip(this, { placement: 'top', trigger: 'hover' });
            });
        }
    }

    $('.flash-close').on('click', function() {
        $(this).closest('.sinagem-alert').fadeOut(300, function() {
            $(this).remove();
        });
    });
});
</script>
@endpush
