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

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

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

        // 1. Tampilkan Data Akun
        public IActionResult Index()
        {
            var dataUsers = _context.AppUsers.ToList();
            return View(dataUsers);
        }

        // 2. Tampilkan Halaman Form Create
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        // 3. Proses Simpan Akun Baru ke Database
        [HttpPost]
        public IActionResult Create(AppUser model)
        {
            try
            {
                // Cek jangan sampai Username kembar
                bool isUsernameExist = _context.AppUsers.Any(u => u.Username.ToLower() == model.Username.ToLower());
                if (isUsernameExist)
                {
                    ViewBag.Error = "GAGAL: Username tersebut sudah terdaftar! Silakan gunakan username lain.";
                    return View(model); // Balikin ke halaman form bawa error
                }

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

                TempData["Success"] = $"MANTAP! Akun untuk {model.FullName} ({model.Role}) berhasil dibuat.";
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ViewBag.Error = $"GAGAL TAMBAH AKUN: Ada data yang tidak sesuai. ({ex.Message})";
                return View(model);
            }
        }

        // 4. Hapus Akun
        [HttpPost]
        public IActionResult Delete(int id)
        {
            try
            {
                var user = _context.AppUsers.Find(id);
                if (user != null)
                {
                    // Cegah Admin hapus dirinya sendiri
                    if (user.Username == User.Identity?.Name)
                    {
                        TempData["Error"] = "GAGAL: Anda tidak bisa menghapus akun yang sedang Anda gunakan saat ini!";
                        return RedirectToAction("Index");
                    }

                    _context.AppUsers.Remove(user);
                    _context.SaveChanges();
                    TempData["Success"] = $"Akun {user.FullName} berhasil dihapus dari sistem.";
                }
            }
            catch (Exception)
            {
                TempData["Error"] = "GAGAL HAPUS: Akun ini masih terikat dengan histori transaksi/request di gudang.";
            }

            return RedirectToAction("Index");
        }

        // 5. Reset Sistem (Sapu Bersih)
        [HttpPost]
        public IActionResult ResetSystem()
        {
            try
            {
                _context.TransactionHistories.RemoveRange(_context.TransactionHistories);
                _context.StockOpnames.RemoveRange(_context.StockOpnames);
                _context.MtcRequests.RemoveRange(_context.MtcRequests);
                _context.ProcurementRequests.RemoveRange(_context.ProcurementRequests);
                _context.MaterialRequests.RemoveRange(_context.MaterialRequests);
                _context.InboundTransactions.RemoveRange(_context.InboundTransactions);
                _context.SaveChanges();

                _context.Materials.RemoveRange(_context.Materials);
                _context.SaveChanges();

                TempData["Success"] = "Sapu Bersih SUKSES! Sistem siap digunakan untuk operasional nyata.";
            }
            catch (Exception ex)
            {
                TempData["Error"] = $"Gagal mereset sistem: Terjadi konflik data. ({ex.Message})";
            }

            return RedirectToAction("Index");
        }
    }
}