using Control_de_datos___KPI.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; namespace Control_de_datos___KPI.Pages.Eventos { public class IndexModel : PageModel { private readonly SistemaKPIContext _context; public IndexModel(SistemaKPIContext context) { _context = context; } [BindProperty] public Evento NuevoEvento { get; set; } = new(); public List ListaEventos { get; set; } = new(); public List ListaClientes { get; set; } = new(); public string? Mensaje { get; set; } [BindProperty] public List ClientesSeleccionados { get; set; } = new(); public async Task CargarListasAsync() { ListaEventos = await _context.Eventos .Include(e => e.EventoClientes) .ThenInclude(ec => ec.IdClienteNavigation) .ToListAsync(); ListaClientes = await _context.Clientes.ToListAsync(); } public async Task OnGetAsync() { await CargarListasAsync(); } public async Task OnPostAsync() { if (!ModelState.IsValid) { await CargarListasAsync(); return Page(); } _context.Eventos.Add(NuevoEvento); await _context.SaveChangesAsync(); foreach (var idcliente in ClientesSeleccionados) { var NuevoEventoC = new EventoCliente { IdEvento = NuevoEvento.IdEvento, IdCliente = idcliente }; _context.EventoClientes.Add(NuevoEventoC); } await _context.SaveChangesAsync(); return RedirectToPage(); } public async Task OnPostEliminarAsync(int id) { var evento = await _context.Eventos.FindAsync(id); var tieneAtenciones = await _context.AtencionEventos .AnyAsync(a => a.IdEvento == id); if (tieneAtenciones) { Mensaje = "No se puede eliminar este evento porque tiene atenciones registradas."; await CargarListasAsync(); return Page(); } if (evento != null) { var relaciones = await _context.EventoClientes .Where(ec => ec.IdEvento == id) .ToListAsync(); _context.EventoClientes.RemoveRange(relaciones); _context.Eventos.Remove(evento); await _context.SaveChangesAsync(); } return RedirectToPage(); } } }