using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Globalization;
using WebVentaCoche.DataBase;
using WebVentaCoche.Enums;
using WebVentaCoche.ViewModels;

namespace WebVentaCoche.Controllers
{
    [Authorize(Roles = "Administrador")]
    public class SalesController : Controller
    {
        private readonly ApplicationDbContext _context;
        public SalesController(ApplicationDbContext context)
        {
            _context = context;
        }

        //GET:/Sales/HistoricalSales
        public IActionResult HistoricalSales()
        {
            return View();
        }

        //GET:/Sales/Last30DaysSales
        public IActionResult Last30DaysSales()
        {
            return View();
        }

        //GET:/Sales/MonthSales
        public async Task<IActionResult> MonthSales()
        {
            var meses = await _context.OrderDetails.Where(d => d.Order.Status == OrderStatus.Delivered)
                .Select(d => new { d.Order.OrderDate.Year, d.Order.OrderDate.Month }).Distinct().ToListAsync();

            ViewBag.Months = meses
                .Select(x => $"{x.Year}-{x.Month:D2}")
                .OrderBy(s => s)
                .ToList();

            return View();
        }        

        [HttpGet]
        public async Task<IActionResult> GetMonthlyData()
        {
            var query =
                from d in _context.OrderDetails
                where d.Order.Status == OrderStatus.Delivered  
                let m = d.Order.OrderDate
                group d by new { d.Product.Name, Year = m.Year, Month = m.Month } into g
                orderby g.Key.Name, g.Key.Year, g.Key.Month
                select new SalesViewModel
                {
                    ProductName = g.Key.Name!,
                    Month = $"{g.Key.Year}-{g.Key.Month:D2}",
                    Units = g.Sum(x => x.Quantity)
                };

            var data = await query.ToListAsync();
            return Json(data);
        }

        [HttpGet]
        public async Task<IActionResult> GetLast30DaysData()
        {
            var desde = DateTime.UtcNow.AddDays(-30);

            var raw = await _context.OrderDetails
                .Where(d => d.Order.Status == OrderStatus.Delivered
                         && d.Order.OrderDate >= desde)
                .GroupBy(d => new
                {
                    d.Product.Name,
                    Date = d.Order.OrderDate.Date
                })
                .Select(g => new
                {
                    ProductName = g.Key.Name!,
                    Date = g.Key.Date,
                    Units = g.Sum(x => x.Quantity)
                })
                .ToListAsync();

            var data = raw
                .Select(x => new
                {
                    productName = x.ProductName,
                    date = x.Date.ToString("yyyy-MM-dd"),
                    units = x.Units
                });

            return Json(data);
        }

        //GET:/Sales/GetMonthData?month=2025-04
        [HttpGet]
        public async Task<IActionResult> GetSalesByMonth(string month)
        {
            if (string.IsNullOrEmpty(month))
                return BadRequest();

            var parts = month.Split('-');
            if (parts.Length != 2 ||
                !int.TryParse(parts[0], out var year) ||
                !int.TryParse(parts[1], out var mon))
            {
                return BadRequest();
            }

            var data = await _context.OrderDetails
                .Where(d =>
                    d.Order.Status == OrderStatus.Delivered &&
                    d.Order.OrderDate.Year == year &&
                    d.Order.OrderDate.Month == mon
                )
                .GroupBy(d => d.Product.Name)
                .Select(g => new
                {
                    productName = g.Key,
                    units = g.Sum(x => x.Quantity),
                    revenue = g.Sum(x => x.Quantity * x.UnitPrice)
                })
                .ToListAsync();

            return Json(data);
        }



    }
}
