using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using WarehouseAppSHIPS.Data;
using System.Linq;
using System;
using Microsoft.EntityFrameworkCore; // Pastikan ini ada

namespace WarehouseAppSHIPS.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly ApplicationDbContext _context;

        public HomeController(ApplicationDbContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            ViewBag.TotalKatalog = _context.Materials.Count();
            ViewBag.TotalStokFisik = _context.Materials.Sum(m => (int?)m.Stock) ?? 0;

            ViewBag.PendingInternal = _context.MaterialRequests.Count(r => r.Status == Models.RequestStatus.Pending);
            ViewBag.PendingEksternal = _context.ProcurementRequests.Count(p => p.IsApproved == null) +
                                       _context.MtcRequests.Count(m => m.IsApproved == null);

            var bulanIni = DateTime.Now.Month;
            var tahunIni = DateTime.Now.Year;

            ViewBag.BarangMasukBulanIni = _context.InboundTransactions
                .Where(i => i.TransactionDate.Month == bulanIni && i.TransactionDate.Year == tahunIni)
                .Sum(i => (int?)i.Qty) ?? 0;

            ViewBag.BarangKeluarBulanIni = _context.MaterialRequests
                .Where(r => r.Status == Models.RequestStatus.Approved && r.RequestDate.Month == bulanIni && r.RequestDate.Year == tahunIni)
                .Sum(r => (int?)r.Qty) ?? 0;

            // === BARU: Ambil Data Stok Kritis (Stok <= MinStock) ===
            ViewBag.StokKritis = _context.Materials
                .Where(m => m.Stock <= m.MinStock)
                .OrderBy(m => m.Stock)
                .ToList();

            var tujuHariLalu = DateTime.Now.Date.AddDays(-6);
            var labelTanggal = new string[7];
            var dataRequest = new int[7];

            for (int i = 0; i < 7; i++)
            {
                var tgl = tujuHariLalu.AddDays(i);
                labelTanggal[i] = tgl.ToString("dd MMM");
                dataRequest[i] = _context.MaterialRequests.Count(r => r.RequestDate.Date == tgl.Date);
            }

            ViewBag.LabelGrafik = labelTanggal;
            ViewBag.DataGrafik = dataRequest;

            return View();
        }
    }
}