@extends('layouts.landing')

@section('title', 'Nuevo Anuncio')

@section('content')
<div class="container-fluid">
    <div class="card shadow mb-4" style="max-width:760px; margin:auto">
        <div class="card-header py-3 d-flex align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-plus-circle mr-1"></i> Nuevo Anuncio
            </h6>
            <a href="{{ route('anuncio.index') }}" class="btn btn-sm btn-secondary">
                <i class="fas fa-arrow-left mr-1"></i> Volver
            </a>
        </div>
        <div class="card-body">

            @if($errors->any())
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        @foreach($errors->all() as $e)
                            <li>{{ $e }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <form action="{{ route('anuncio.store') }}" method="POST" enctype="multipart/form-data">
                @csrf

                {{-- Título --}}
                <div class="form-group">
                    <label class="font-weight-bold">Título <span class="text-danger">*</span></label>
                    <input type="text" name="title" class="form-control @error('title') is-invalid @enderror"
                           value="{{ old('title') }}" maxlength="200" placeholder="Título del anuncio" required>
                    @error('title')<div class="invalid-feedback">{{ $message }}</div>@enderror
                </div>

                {{-- Cuerpo --}}
                <div class="form-group">
                    <label class="font-weight-bold">Descripción</label>
                    <textarea name="body" class="form-control @error('body') is-invalid @enderror"
                              rows="4" maxlength="3000" placeholder="Texto del anuncio (opcional)">{{ old('body') }}</textarea>
                    @error('body')<div class="invalid-feedback">{{ $message }}</div>@enderror
                </div>

                {{-- Tipo --}}
                <div class="form-group">
                    <label class="font-weight-bold">Tipo <span class="text-danger">*</span></label>
                    <div class="d-flex flex-wrap gap-2">
                        @foreach($types as $key => $cfg)
                            <div class="form-check form-check-inline mr-3">
                                <input class="form-check-input" type="radio" name="type" id="type_{{ $key }}"
                                       value="{{ $key }}" {{ old('type', 'info') === $key ? 'checked' : '' }} required>
                                <label class="form-check-label" for="type_{{ $key }}">
                                    <span class="badge badge-{{ $cfg['color'] }}">
                                        <i class="fas {{ $cfg['icon'] }} mr-1"></i>{{ $cfg['label'] }}
                                    </span>
                                </label>
                            </div>
                        @endforeach
                    </div>
                    @error('type')<div class="text-danger small mt-1">{{ $message }}</div>@enderror
                </div>

                {{-- Audiencia --}}
                <div class="form-group">
                    <label class="font-weight-bold">Audiencia <span class="text-danger">*</span></label>
                    <div class="border rounded p-3 bg-light">
                        <div class="row">
                            @foreach($roles as $key => $label)
                                <div class="col-6 col-md-4">
                                    <div class="form-check">
                                        <input class="form-check-input audience-check" type="checkbox"
                                               name="audience[]" id="aud_{{ $key }}" value="{{ $key }}"
                                               {{ in_array($key, old('audience', [])) ? 'checked' : '' }}>
                                        <label class="form-check-label" for="aud_{{ $key }}">{{ $label }}</label>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                    @error('audience')<div class="text-danger small mt-1">{{ $message }}</div>@enderror
                </div>

                {{-- Imagen --}}
                <div class="form-group">
                    <label class="font-weight-bold">Imagen</label>
                    <div class="custom-file">
                        <input type="file" class="custom-file-input @error('image') is-invalid @enderror"
                               id="imageInput" name="image" accept="image/*">
                        <label class="custom-file-label" for="imageInput">Seleccionar imagen (máx. 5 MB)</label>
                    </div>
                    @error('image')<div class="text-danger small mt-1">{{ $message }}</div>@enderror
                    <div id="imagePreview" class="mt-2 d-none">
                        <img id="previewImg" src="" alt="Vista previa" class="img-fluid rounded" style="max-height:200px">
                    </div>
                </div>

                {{-- Vencimiento --}}
                <div class="form-group">
                    <label class="font-weight-bold">Fecha de vencimiento</label>
                    <input type="datetime-local" name="expires_at"
                           class="form-control @error('expires_at') is-invalid @enderror"
                           value="{{ old('expires_at') }}">
                    <small class="text-muted">Dejar vacío para que no tenga vencimiento.</small>
                    @error('expires_at')<div class="invalid-feedback">{{ $message }}</div>@enderror
                </div>

                {{-- Activo --}}
                <div class="form-group">
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="activeSwitch"
                               name="active" value="1" {{ old('active', '1') ? 'checked' : '' }}>
                        <label class="custom-control-label font-weight-bold" for="activeSwitch">Publicar inmediatamente</label>
                    </div>
                </div>

                <hr>
                <div class="d-flex justify-content-end">
                    <a href="{{ route('anuncio.index') }}" class="btn btn-secondary mr-2">Cancelar</a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save mr-1"></i> Guardar anuncio
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
    // Custom file label
    document.getElementById('imageInput').addEventListener('change', function () {
        const file = this.files[0];
        this.nextElementSibling.textContent = file ? file.name : 'Seleccionar imagen (máx. 5 MB)';
        if (file) {
            const reader = new FileReader();
            reader.onload = e => {
                document.getElementById('previewImg').src = e.target.result;
                document.getElementById('imagePreview').classList.remove('d-none');
            };
            reader.readAsDataURL(file);
        } else {
            document.getElementById('imagePreview').classList.add('d-none');
        }
    });

    // "Todos" exclusivo con los demás
    document.querySelectorAll('.audience-check').forEach(function (cb) {
        cb.addEventListener('change', function () {
            if (this.value === 'all' && this.checked) {
                document.querySelectorAll('.audience-check').forEach(c => { if (c !== this) c.checked = false; });
            } else if (this.value !== 'all' && this.checked) {
                const allCb = document.querySelector('.audience-check[value="all"]');
                if (allCb) allCb.checked = false;
            }
        });
    });
</script>
@endsection
