using ClosedXML.Excel;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using WarehouseAppSHIPS.Data;
using WarehouseAppSHIPS.Models;
using System.Linq;
using System;

namespace WarehouseAppSHIPS.Controllers
{
    [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
    public class StockOpnameController : Controller
    {
        private readonly ApplicationDbContext _context;

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

        public IActionResult Index()
        {
            var data = _context.StockOpnames
                .Include(s => s.Material)
                .Include(s => s.Auditor)
                .OrderByDescending(s => s.AuditDate)
                .ToList();
            return View(data);
        }

        public IActionResult Create()
        {
            var materialList = _context.Materials.Select(m => new
            {
                Id = m.Id,
                DisplayInfo = $"{m.AssetCode} - {m.Name} (Sistem: {m.Stock})"
            }).ToList();

            ViewBag.MaterialList = new SelectList(materialList, "Id", "DisplayInfo");
            return View();
        }

        [HttpPost]
        public IActionResult Create(StockOpname model)
        {
            var material = _context.Materials.Find(model.MaterialId);
            if (material != null)
            {
                var userId = int.Parse(User.FindFirstValue("UserId") ?? "1");

                model.AuditorId = userId;
                model.AuditDate = DateTime.Now;
                model.SystemStock = material.Stock;
                model.Difference = model.PhysicalStock - material.Stock;

                material.Stock = model.PhysicalStock;

                _context.StockOpnames.Add(model);

                // === OTOMATIS MASUK KE HISTORI TRANSAKSI INDUK ===
                var historyLog = new TransactionHistory
                {
                    TransactionDate = DateTime.Now,
                    TransactionType = "STOCK OPNAME",
                    MaterialName = material.Name,
                    AssetCode = material.AssetCode ?? "-",
                    Qty = model.Difference,
                    ActorName = User.Identity?.Name ?? "Auditor",
                    Remarks = $"Audit fisik gudang. Stok sistem: {model.SystemStock}, Fisik terhitung: {model.PhysicalStock}. Catatan: {(model.Remarks ?? "")}"
                };
                _context.TransactionHistories.Add(historyLog);

                _context.SaveChanges();

                TempData["Success"] = $"Stock Opname Selesai! Stok {material.Name} telah disesuaikan menjadi {model.PhysicalStock}. Selisih: {model.Difference}.";
                return RedirectToAction("Index");
            }
            return View(model);
        }

        [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
        public IActionResult ExportStockOpnameExcel()
        {
            var dataOpname = _context.StockOpnames
                .Include(s => s.Material)
                .Include(s => s.Auditor)
                .OrderByDescending(s => s.AuditDate)
                .ToList();

            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("Riwayat Stock Opname");
                var currentRow = 1;

                worksheet.Cell(currentRow, 1).Value = "Tanggal Audit";
                worksheet.Cell(currentRow, 2).Value = "Kode Aset";
                worksheet.Cell(currentRow, 3).Value = "Nama Material";
                worksheet.Cell(currentRow, 4).Value = "Stok Sistem";
                worksheet.Cell(currentRow, 5).Value = "Stok Fisik";
                worksheet.Cell(currentRow, 6).Value = "Selisih";
                worksheet.Cell(currentRow, 7).Value = "Auditor";
                worksheet.Cell(currentRow, 8).Value = "Catatan";

                foreach (var item in dataOpname)
                {
                    currentRow++;
                    worksheet.Cell(currentRow, 1).Value = item.AuditDate.ToString("dd-MM-yyyy HH:mm");
                    worksheet.Cell(currentRow, 2).Value = item.Material?.AssetCode ?? "-";
                    worksheet.Cell(currentRow, 3).Value = item.Material?.Name ?? "-";
                    worksheet.Cell(currentRow, 4).Value = item.SystemStock;
                    worksheet.Cell(currentRow, 5).Value = item.PhysicalStock;
                    worksheet.Cell(currentRow, 6).Value = item.Difference;
                    worksheet.Cell(currentRow, 7).Value = item.Auditor?.FullName ?? "-";
                    worksheet.Cell(currentRow, 8).Value = item.Remarks ?? "-";
                }

                worksheet.Columns().AdjustToContents();

                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Riwayat_Stock_Opname_SHIPS.xlsx");
                }
            }
        }
    }
}