using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using WarehouseAppSHIPS.Data;
using System.Linq;
using System.Security.Claims;

namespace WarehouseAppSHIPS.Controllers
{
    [Authorize] // Semua user yang login boleh masuk ke sini
    public class ProfileController : Controller
    {
        private readonly ApplicationDbContext _context;

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

        // 1. Tampilkan Halaman Profil
        [HttpGet]
        public IActionResult Index()
        {
            // Ambil ID user dari sesi login
            var userIdClaim = User.FindFirstValue("UserId");
            if (userIdClaim == null) return RedirectToAction("Login", "Account");

            int userId = int.Parse(userIdClaim);
            var user = _context.AppUsers.Find(userId);

            if (user == null) return NotFound();

            return View(user);
        }

        // 2. Proses Ganti Password
        [HttpPost]
        public IActionResult ChangePassword(string oldPassword, string newPassword, string confirmPassword)
        {
            var userIdClaim = User.FindFirstValue("UserId");
            if (userIdClaim == null) return RedirectToAction("Login", "Account");

            int userId = int.Parse(userIdClaim);
            var user = _context.AppUsers.Find(userId);

            if (user == null) return NotFound();

            // Cek apakah password lama yang dimasukkan sesuai
            if (user.PasswordHash != oldPassword)
            {
                TempData["Error"] = "GAGAL: Password lama yang Anda masukkan salah!";
                return RedirectToAction("Index");
            }

            // Cek apakah password baru dan konfirmasi cocok
            if (newPassword != confirmPassword)
            {
                TempData["Error"] = "GAGAL: Password baru dan konfirmasi password tidak sama!";
                return RedirectToAction("Index");
            }

            // Simpan password baru
            user.PasswordHash = newPassword;
            _context.SaveChanges();

            TempData["Success"] = "SUKSES: Password berhasil diubah! Silakan gunakan password baru pada login berikutnya.";
            return RedirectToAction("Index");
        }
    }
}