package com.seyalix.hr.utils

import android.content.Context

class PrefsManager(ctx: Context) {
    private val p = ctx.getSharedPreferences("hr_prefs", Context.MODE_PRIVATE)

    fun saveLogin(token: String, empId: Int, name: String, role: String, empCode: String, photo: String?) {
        p.edit()
            .putString("token", token)
            .putInt("emp_id", empId)
            .putString("name", name)
            .putString("role", role)
            .putString("emp_code", empCode)
            .putString("photo", photo)
            .putBoolean("logged_in", true)
            .apply()
    }

    fun getToken(): String  = p.getString("token", "") ?: ""
    fun getEmpId(): Int     = p.getInt("emp_id", 0)
    fun getName(): String   = p.getString("name", "") ?: ""
    fun getRole(): String   = p.getString("role", "employee") ?: "employee"
    fun getEmpCode(): String = p.getString("emp_code", "") ?: ""
    fun getPhoto(): String? = p.getString("photo", null)
    fun isLoggedIn(): Boolean = p.getBoolean("logged_in", false)

    // Role helpers
    fun isEmployee()    = getRole() == "employee"
    fun isManager()     = getRole() == "manager"
    fun isHr()          = getRole() == "hr"
    fun isAdmin()       = getRole() == "admin"
    fun isSuperAdmin()  = getRole() == "superadmin"

    // Can approve: manager, hr, admin, superadmin
    fun canApprove()    = getRole() in listOf("manager", "hr", "admin", "superadmin")

    // Management level: admin + superadmin see ALL pending (not just their team)
    fun isManagement()  = getRole() in listOf("admin", "superadmin")

    // Senior head = hr + admin + superadmin (need a second approval layer)
    fun isSeniorHead()  = getRole() in listOf("hr", "admin", "superadmin")

    // Last pending-approval count we already notified this head about, so
    // polling only pops a notification for genuinely NEW items, not the
    // same backlog every 30 seconds.
    fun getLastSeenApprovalCount(): Int = p.getInt("last_seen_approval_count", 0)
    fun setLastSeenApprovalCount(count: Int) = p.edit().putInt("last_seen_approval_count", count).apply()

    // FIX (10 Jul 2026): same idea, for personal notifications (everyone
    // gets these, not just approvers) — tracks what this device has
    // already popped a notification for, so re-polling doesn't re-alert
    // about the same unread backlog every 30 seconds.
    fun getLastSeenNotifCount(): Int = p.getInt("last_seen_notif_count", 0)
    fun setLastSeenNotifCount(count: Int) = p.edit().putInt("last_seen_notif_count", count).apply()

    fun logout() = p.edit().clear().apply()
}
