using ClosedXML.Excel;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Linq;
using System;
using WarehouseAppSHIPS.Data;
using WarehouseAppSHIPS.Models;

namespace WarehouseAppSHIPS.Controllers
{
    // Hanya orang gudang dan manajemen yang boleh melihat buku besar ini
    [Authorize(Roles = "MasterAdmin,Supervisor,StaffGudang")]
    public class HistoryController : Controller
    {
        private readonly ApplicationDbContext _context;

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

        // 1. Tampilkan ke Layar Web (Langsung tembak ke Tabel Induk)
        public IActionResult Index()
        {
            var data = _context.TransactionHistories
                .OrderByDescending(h => h.TransactionDate)
                .ToList();
            return View(data);
        }

        // 2. FITUR BARU: Download ke Excel Murni (.xlsx) pakai ClosedXML
        public IActionResult ExportExcel()
        {
            var data = _context.TransactionHistories
                .OrderByDescending(h => h.TransactionDate)
                .ToList();

            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("Log Aktivitas Pusat");
                var currentRow = 1;

                // --- BIKIN HEADER KOLOM ---
                worksheet.Cell(currentRow, 1).Value = "WAKTU TRANSAKSI";
                worksheet.Cell(currentRow, 2).Value = "JENIS AKTIVITAS";
                worksheet.Cell(currentRow, 3).Value = "KODE ASET";
                worksheet.Cell(currentRow, 4).Value = "NAMA MATERIAL";
                worksheet.Cell(currentRow, 5).Value = "QTY / VOLUME";
                worksheet.Cell(currentRow, 6).Value = "OPERATOR (AKTOR)";
                worksheet.Cell(currentRow, 7).Value = "KETERANGAN LOG";

                // --- MASUKIN DATANYA ---
                foreach (var item in data)
                {
                    currentRow++;
                    worksheet.Cell(currentRow, 1).Value = item.TransactionDate.ToString("dd-MM-yyyy HH:mm");
                    worksheet.Cell(currentRow, 2).Value = item.TransactionType ?? "-";
                    worksheet.Cell(currentRow, 3).Value = item.AssetCode ?? "-";
                    worksheet.Cell(currentRow, 4).Value = item.MaterialName ?? "-";

                    // Kalau minus (barang keluar) tetep keliatan jelas angkanya
                    worksheet.Cell(currentRow, 5).Value = item.Qty;

                    worksheet.Cell(currentRow, 6).Value = item.ActorName ?? "-";
                    worksheet.Cell(currentRow, 7).Value = item.Remarks ?? "-";
                }

                // --- RAPIKAN LEBAR KOLOM OTOMATIS ---
                worksheet.Columns().AdjustToContents();

                // 3. Convert ke memory stream dan lempar ke browser sebagai .xlsx
                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    var content = stream.ToArray();

                    return File(
                        content,
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        $"Histori_Transaksi_Pusat_SHIPS_{DateTime.Now.ToString("ddMMyyyy")}.xlsx"
                    );
                }
            }
        }
    }
}