@extends('layouts.landing')

@section('title', 'Editar 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-edit mr-1"></i> Editar 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.update', $anuncio) }}" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')

                {{-- 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', $anuncio->title) }}" maxlength="200" 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">{{ old('body', $anuncio->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">
                        @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', $anuncio->type) === $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', $anuncio->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 actual + nueva --}}
                <div class="form-group">
                    <label class="font-weight-bold">Imagen</label>
                    @if($anuncio->image_path)
                        <div class="mb-2">
                            <img src="{{ Storage::url($anuncio->image_path) }}" alt="Imagen actual"
                                 class="img-fluid rounded" style="max-height:150px">
                            <div class="form-check mt-1">
                                <input class="form-check-input" type="checkbox" name="remove_image" id="removeImage" value="1">
                                <label class="form-check-label text-danger" for="removeImage">Eliminar imagen actual</label>
                            </div>
                        </div>
                    @endif
                    <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">
                            {{ $anuncio->image_path ? 'Reemplazar imagen (máx. 5 MB)' : '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', $anuncio->expires_at ? $anuncio->expires_at->format('Y-m-d\TH:i') : '') }}">
                    <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', $anuncio->active) ? 'checked' : '' }}>
                        <label class="custom-control-label font-weight-bold" for="activeSwitch">Anuncio activo</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> Actualizar anuncio
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
    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');
        }
    });

    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
