using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Security.Claims;
using WarehouseAppSHIPS.Data;
using WarehouseAppSHIPS.Models;

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

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

        // 1. Tampilan Utama Histori Barang Keluar (TIDAK PAKAI FILTER)
        public IActionResult Index()
        {
            var data = _context.OutboundTransactions
                .Include(o => o.Material)
                .Include(o => o.Issuer)
                .OrderByDescending(o => o.TransactionDate)
                .ToList();

            return View(data);
        }

        // 2. Halaman Form Keluarkan Barang
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Create()
        {
            ViewBag.MaterialList = new SelectList(_context.Materials.Where(m => m.Stock > 0).ToList(), "Id", "Name");
            return View();
        }

        // 3. Proses Keluarkan Barang & Kurangi Stok Fisik
        [HttpPost]
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Create(OutboundTransaction model)
        {
            var userId = int.Parse(User.FindFirstValue("UserId") ?? "1");
            model.IssuerId = userId;
            model.TransactionDate = DateTime.Now;

            var material = _context.Materials.Find(model.MaterialId);
            if (material != null)
            {
                // Cek apakah stok cukup
                if (material.Stock < model.Qty)
                {
                    TempData["Error"] = $"GAGAL! Stok {material.Name} tidak mencukupi. Sisa stok saat ini: {material.Stock}";
                    ViewBag.MaterialList = new SelectList(_context.Materials.Where(m => m.Stock > 0).ToList(), "Id", "Name");
                    return View(model);
                }

                material.Stock -= model.Qty; // Kurangi stok
            }

            _context.OutboundTransactions.Add(model);
            _context.SaveChanges();

            TempData["Success"] = "Barang berhasil dikeluarkan dan stok gudang otomatis berkurang!";
            return RedirectToAction("Index");
        }

        // 4. Hapus Histori Keluar (Otomatis mengembalikan stok yang batal keluar)
        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult Delete(int id)
        {
            var transaction = _context.OutboundTransactions.Find(id);
            if (transaction != null)
            {
                var material = _context.Materials.Find(transaction.MaterialId);
                if (material != null)
                {
                    material.Stock += transaction.Qty; // Kembalikan stok yang salah dikeluarkan
                }

                _context.OutboundTransactions.Remove(transaction);
                _context.SaveChanges();
                TempData["Success"] = "Histori pengeluaran dibatalkan. Stok barang telah dikembalikan ke sistem!";
            }
            return RedirectToAction("Index");
        }
    }
}