
-- Realistic Police Helix Sync
-- Created to restrict computer to FSB and sync wanted status with Military ID

local FSB_PODR_ID = 6

Realistic_Police = Realistic_Police or {}

-- New helper to get the job name, respecting Helix units (podrazdeneniya)
function Realistic_Police.GetPlayerJob(ply)
    if not IsValid(ply) then return "" end
    local char = ply.GetCharacter and ply:GetCharacter()
    if not char then return team.GetName(ply:Team()) end
    
    -- In this server, if the faction is FACTION_RUSSIAN, we check the unit ID
    if char:GetFaction() == (FACTION_RUSSIAN or -1) then
        local podrId = char:GetPodr()
        if podrId == FSB_PODR_ID then
            return "ФСБ  «Вымпел»" -- Note: must match config exactly (2 spaces)
        end
    end
    
    return team.GetName(ply:Team())
end

if SERVER then
    local plyMeta = FindMetaTable("Player")

    -- Define wanted status for players in Helix
    function plyMeta:isWanted()
        local char = self:GetCharacter()
        if not char then return false end
        return char:GetData("wanted", false)
    end

    function plyMeta:wanted(actor, reason, duration)
        local char = self:GetCharacter()
        if not char then return end
        char:SetData("wanted", true)
        char:SetData("wanted_reason", reason or "Розыск ФСБ")
        
        -- Custom long-term wanted logic: we ignore duration and keep it until manual removal
        net.Start("RealisticPolice:Open")
            net.WriteString("Notify")
            net.WriteString(self:Name() .. " теперь находится в розыске!")
        net.Broadcast()
    end

    function plyMeta:unWanted(actor)
        local char = self:GetCharacter()
        if not char then return end
        char:SetData("wanted", false)
        char:SetData("wanted_reason", nil)

        net.Start("RealisticPolice:Open")
            net.WriteString("Notify")
            net.WriteString(self:Name() .. " снят с розыска.")
        net.Broadcast()
    end

    -- Hook into say commands if the police addon uses them
    hook.Add("PlayerSay", "RealisticPolice_WantedCommands", function(ply, text)
        local lowText = string.lower(text)
        local isWanted = string.StartWith(lowText, "/wanted") or string.StartWith(lowText, "!wanted")
        local isUnwanted = string.StartWith(lowText, "/unwanted") or string.StartWith(lowText, "!unwanted")
        
        if isWanted or isUnwanted then
            -- Permission check
            local job = Realistic_Police.GetPlayerJob(ply)
            if not Realistic_Police.OpenComputer[job] and not Realistic_Police.AdminRank[ply:GetUserGroup()] then
                return
            end

            -- Parse Name and Reason
            local cmd = isWanted and (string.StartWith(lowText, "/wanted") and "/wanted" or "!wanted") or (string.StartWith(lowText, "/unwanted") and "/unwanted" or "!unwanted")
            local fullParams = string.Trim(string.sub(text, #cmd + 1))
            
            local target = nil
            local reason = ""
            
            -- Find the player whose name matches the start of fullParams
            for _, v in pairs(player.GetAll()) do
                local name = v:Name()
                if string.StartWith(fullParams, name) then
                    -- If multiple players match (e.g. "Ivan" and "Ivan Ivanov"), we want the longest match
                    if not target or #name > #target:Name() then
                        target = v
                        reason = string.Trim(string.sub(fullParams, #name + 1))
                    end
                end
            end
            
            if target then
                if isWanted then
                    target:wanted(ply, reason)
                else
                    target:unWanted(ply)
                end
                return "" -- Hide from chat
            end
        end
    end)
    
    -- Robust server-side check for opening the computer
    hook.Add("PlayerUse", "RealisticPolice_FSBRestrict", function(ply, ent)
        if IsValid(ent) and ent:GetClass() == "realistic_police_computer" then
            local job = Realistic_Police.GetPlayerJob(ply)
            if not Realistic_Police.OpenComputer[job] and not Realistic_Police.AdminRank[ply:GetUserGroup()] then
                if not (Realistic_Police.HackerJob and Realistic_Police.HackerJob[job]) then
                    Realistic_Police.SendNotify(ply, "Доступ к компьютеру разрешен только подразделению ФСБ!")
                    return false
                end
            end
        end
    end)
end

if CLIENT then
    -- Override the computer open check to restrict to FSB
    timer.Simple(1, function()
        if not Realistic_Police then return end

        local oldOpenMenu = Realistic_Police.OpenMenu
        Realistic_Police.OpenMenu = function(ent, bool)
            local job = Realistic_Police.GetPlayerJob(LocalPlayer())
            if not Realistic_Police.OpenComputer[job] and not Realistic_Police.AdminRank[LocalPlayer():GetUserGroup()] then
                if not (Realistic_Police.HackerJob and Realistic_Police.HackerJob[job]) then
                    RealisticPoliceNotify("Доступ запрещен. Только для подразделения ФСБ.")
                    return
                end
            end
            oldOpenMenu(ent, bool)
        end
    end)
end
