AddCSLuaFile("shared.lua")
include("shared.lua")

util.AddNetworkString("MuR_DroneCam")
util.AddNetworkString("MuR_DroneLost")
util.AddNetworkString("MuR_DroneEmergency") -- экстренное самоуничтожение

local rotorSounds = {
    "ambient/machines/spin_loop.wav",
    "ambient/machines/machine1_hit1.wav"
}

local damageSounds = {
    "physics/metal/metal_box_impact_bullet1.wav",
    "physics/metal/metal_box_impact_bullet2.wav",
    "physics/metal/metal_box_impact_bullet3.wav",
    "physics/metal/metal_computer_impact_bullet1.wav",
    "physics/metal/metal_computer_impact_bullet2.wav"
}

local startupSounds = {
    "buttons/button9.wav",
    "buttons/button17.wav"
}

function ENT:Initialize()
    self:SetModel("models/murdered/weapons/drone_ex.mdl")
    self:ResetSequence("idle")
    self:SetHealth(self.HealthCount)
    self:SetGravity(0)
    self.Velo = {x = 0, y = 0, z = 0}

    self:SetSolid(SOLID_VPHYSICS)
    self:PhysicsInit(SOLID_VPHYSICS)

    self.MultSpeed = 900
    self.MaxSpeed = 1000
    self.BoostSpeed = 1500
    self.MaxPitch = 18
    self.MaxRoll = 22
    self.LinearDrag = 0.04
    self.GrenadeDelay = CurTime() + 5
    self.TakeDamageWall = 0
    self.DeltaTime = 0
    self.LastBoostSound = 0
    self.LastWindSound = 0

    -- самоуничтожение
    self.EmergencyKill = false
    self.EmergencyKillTime = 0
    self._Exploding = false
    self:SetNW2Float("EmergencyCountdown", 0)

    self:SetNW2Float("RemoveTime", CurTime() + self.BatteryCount)

    self:EmitSound(startupSounds[math.random(#startupSounds)], 60, 100, 0.5)

    local ply = self:GetCreator()
    if IsValid(ply) then
        local forward = ply:GetForward()
        forward.z = 0
        forward = forward:GetNormalized()

        local spawnDist = 80
        local spawnHeight = 40

        local spawnPos = ply:GetPos() + forward * spawnDist + Vector(0, 0, spawnHeight)

        local tr = util.TraceHull({
            start = spawnPos,
            endpos = spawnPos,
            mins = Vector(-20, -20, -20),
            maxs = Vector(20, 20, 20),
            filter = {ply, self}
        })

        if tr.Hit then
            spawnPos = spawnPos + forward * 60
        end

        local ground = util.TraceLine({
            start = spawnPos,
            endpos = spawnPos - Vector(0, 0, 5000),
            filter = self
        })

        if spawnPos.z < ground.HitPos.z + 30 then
            spawnPos.z = ground.HitPos.z + 30
        end

        self:SetPos(spawnPos)
        self:SetAngles(Angle(0, ply:EyeAngles().y, 0))
    end

    -- визуальная ПГ-26 под дроном
    local rocket = ents.Create("prop_dynamic")
    if IsValid(rocket) then
        rocket:SetModel("models/sw/rus/rockets/pg26.mdl")
        rocket:SetParent(self)
        rocket:SetLocalPos(Vector(-15, 0, 2))
        rocket:SetLocalAngles(Angle(0, 0, 0))
        rocket:Spawn()
        rocket:SetMoveType(MOVETYPE_NONE)
        rocket:SetSolid(SOLID_NONE)
        rocket:PhysicsDestroy()
        self.RocketModel = rocket
    end

    if CreateSound then
        self.RotorSound = CreateSound(self, rotorSounds[1])
        if self.RotorSound then
            self.RotorSound:PlayEx(0.2, 80)
        end

        self.WindSound = CreateSound(self, "ambient/wind/wind_snippet2.wav")
        if self.WindSound then
            self.WindSound:PlayEx(0, 100)
        end
    end

    timer.Simple(0.1, function()
        if not IsValid(self) then return end
        local ply2 = self:GetCreator()
        if not IsValid(ply2) then return end

        ply2.ControlDrone = self

        net.Start("MuR_DroneCam")
        net.WriteEntity(self)
        net.Send(ply2)
    end)
end

function ENT:OnRemove()
    local ply = self:GetCreator()
    if IsValid(ply) and ply.ControlDrone == self then
        ply.ControlDrone = nil
    end

    if self.RotorSound then self.RotorSound:Stop() end
    if self.WindSound then self.WindSound:Stop() end
    self:StopSound("ambient/machines/spin_loop.wav")
    self:StopSound("ambient/wind/wind_snippet2.wav")
    self:StopSound("vehicles/airboat/fan_blade_fullthrottle_loop1.wav")
end

function ENT:GetForwardAbs()
    local ang = self:GetAngles()
    ang.x = 0
    ang.z = 0
    return ang:Forward()
end

function ENT:GetRightAbs()
    local ang = self:GetAngles()
    ang.x = 0
    ang.z = 0
    return ang:Right()
end

function ENT:GetUpAbs()
    local ang = self:GetAngles()
    ang.x = 0
    ang.z = 0
    return ang:Up()
end

function ENT:Think()
    -- самоуничтожение
    if self.EmergencyKill then
        local phys = self:GetPhysicsObject()
        if IsValid(phys) then
            phys:EnableMotion(false)
        end

        if CurTime() >= (self.EmergencyKillTime or 0) then
            self:Explode()
            return true
        end
    end

    -- Ограничение дистанции как у spy-дрона
    local ply = self:GetCreator()
    if IsValid(ply) then
        local maxDist = 12000 * 12000 -- 12к юнитов
        local dist2 = ply:GetPos():DistToSqr(self:GetPos())

        if dist2 > maxDist then
            net.Start("MuR_DroneLost")
            net.Send(ply)

            if ply.ControlDrone == self then
                ply.ControlDrone = nil
            end

            self:Explode()
            return true
     end
    end

    -- === РЭБ (глушилка) ===
    if self:GetNWBool("Jammed") then

    -- если впервые попали в РЭБ — запускаем таймер
        if not self.JamStart then
            self.JamStart = CurTime()
            self.JamEnd = CurTime() + 5   -- 5 секунд на выход
        end

    -- ВАЖНО: управление НЕ отключаем
    -- ВАЖНО: скорость НЕ сбрасываем
    -- Дрон продолжает лететь как обычно

    -- если время вышло — взрываем
        if CurTime() >= self.JamEnd then
            local ply = self:GetCreator()
            if IsValid(ply) then
                net.Start("MuR_DroneLost")
                net.Send(ply)
                if ply.ControlDrone == self then
                    ply.ControlDrone = nil
                end
            end

            self:Explode()
            return true
        end

    else
    -- если вышли из РЭБ — сбрасываем таймер
        self.JamStart = nil
        self.JamEnd = nil
    end



    local ply = self:GetCreator()
    if not IsValid(ply) then
        self:Remove()
        return
    end

    local phys = self:GetPhysicsObject()
    local mu   = self.MultSpeed
    local ms   = self.MaxSpeed
    local tick = FrameTime()
    local ang  = ply:EyeAngles().y
    local sang = Angle(0, ang, 0)

    ply:SetActiveWeapon(nil)

    local tr = util.TraceEntity({
        start = self:GetPos(),
        endpos = self:GetPos(),
        filter = self
    }, self)

    if self:GetNW2Bool("Boost") then
        local fwd = self:GetForward()
        phys:SetVelocityInstantaneous(fwd * self.Velo.x)
    else
        if tr.Hit then
            phys:SetVelocityInstantaneous(
                (self:GetForwardAbs() * self.Velo.x +
                 self:GetRightAbs()   * self.Velo.y +
                 self:GetUpAbs()      * self.Velo.z) / 2
            )
            if self.TakeDamageWall < CurTime() then
                self:TakeDamage(1)
                self.TakeDamageWall = CurTime() + 0.2
            end
        else
            phys:SetVelocityInstantaneous(
                self:GetForwardAbs() * self.Velo.x +
                self:GetRightAbs()   * self.Velo.y +
                self:GetUpAbs()      * self.Velo.z +
                Vector(0, 0, 15)
            )
        end
    end

    local ratioX = math.Clamp(self.Velo.x / ms, -1, 1)
    local ratioY = math.Clamp(self.Velo.y / ms, -1, 1)
    local targetPitch = ratioX * self.MaxPitch
    local targetRoll  = ratioY * self.MaxRoll
    sang = Angle(targetPitch, ang, targetRoll)

    local b = {}
    b.secondstoarrive = 1
    b.pos             = self:GetPos()
    b.angle           = sang
    b.maxangular      = 120
    b.maxangulardamp  = 50
    b.maxspeed        = 1000
    b.maxspeeddamp    = 150
    b.dampfactor      = 0.4
    b.teleportdistance= 0
    b.deltatime       = CurTime() - self.DeltaTime
    phys:ComputeShadowControl(b)

    if ply:KeyDown(IN_FORWARD) or self:GetNW2Bool("Boost") then
        if self:GetNW2Bool("Boost") then
            self.Velo.x = math.Clamp(self.Velo.x + tick * mu * 2, -ms, self.BoostSpeed)
        else
            self.Velo.x = math.Clamp(self.Velo.x + tick * mu, -ms, ms)
        end
    elseif ply:KeyDown(IN_BACK) then
        self.Velo.x = math.Clamp(self.Velo.x - tick * mu, -ms, ms)
    end

    if ply:KeyDown(IN_MOVELEFT) then
        self.Velo.y = math.Clamp(self.Velo.y - tick * mu, -ms, ms)
    elseif ply:KeyDown(IN_MOVERIGHT) then
        self.Velo.y = math.Clamp(self.Velo.y + tick * mu, -ms, ms)
    end

    if ply:KeyDown(IN_DUCK) then
        self.Velo.z = math.Clamp(self.Velo.z - tick * mu, -ms, ms)
    elseif ply:KeyDown(IN_SPEED) then
        self.Velo.z = math.Clamp(self.Velo.z + tick * mu, -ms, ms)
    end

    local drag = 1 - math.Clamp(self.LinearDrag * tick, 0, 0.2)
    self.Velo.x = self.Velo.x * drag
    self.Velo.y = self.Velo.y * drag
    self.Velo.z = self.Velo.z * (0.98 * drag)

    if not ply:KeyDown(IN_FORWARD) and not ply:KeyDown(IN_BACK) and not self:GetNW2Bool("Boost") then
        if math.abs(self.Velo.x) > 5 then
            if self.Velo.x > 0 then
                self.Velo.x = math.Clamp(self.Velo.x - tick * mu, -ms, ms)
            else
                self.Velo.x = math.Clamp(self.Velo.x + tick * mu, -ms, ms)
            end
        else
            self.Velo.x = 0
        end
    end

    if not ply:KeyDown(IN_SPEED) and not ply:KeyDown(IN_DUCK) then
        if math.abs(self.Velo.z) > 5 then
            if self.Velo.z > 0 then
                self.Velo.z = math.Clamp(self.Velo.z - tick * mu, -ms, ms)
            else
                self.Velo.z = math.Clamp(self.Velo.z + tick * mu, -ms, ms)
            end
        else
            self.Velo.z = 0
        end
    end

    if not ply:KeyDown(IN_MOVELEFT) and not ply:KeyDown(IN_MOVERIGHT) then
        if math.abs(self.Velo.y) > 5 then
            if self.Velo.y > 0 then
                self.Velo.y = math.Clamp(self.Velo.y - tick * mu, -ms, ms)
            else
                self.Velo.y = math.Clamp(self.Velo.y + tick * mu, -ms, ms)
            end
        else
            self.Velo.y = 0
        end
    end

    local wasBoost = self:GetNW2Bool("Boost")
    self:SetNW2Bool("Boost", ply:KeyDown(IN_ATTACK))
    self:SetNW2Bool("Light", ply:KeyDown(IN_ATTACK2))

    if ply:KeyDown(IN_ATTACK) and not wasBoost then
        self:EmitSound("vehicles/airboat/fan_blade_fullthrottle_loop1.wav", 70, 150, 0.4)
        self.LastBoostSound = CurTime()
    elseif not ply:KeyDown(IN_ATTACK) and wasBoost then
        self:StopSound("vehicles/airboat/fan_blade_fullthrottle_loop1.wav")
    end

    if self.RotorSound then
        local spd = phys:GetVelocity():Length()
        local load = math.Clamp(
            (math.abs(self.Velo.x) + math.abs(self.Velo.y) + math.abs(self.Velo.z)) / (self.BoostSpeed * 0.6),
            0, 1
        )
        local timeLeft = math.max(self:GetNW2Float("RemoveTime") - CurTime(), 0)
        local battFrac = math.Clamp(timeLeft / self.BatteryCount, 0, 1)
        local basePitch = 80 + 45 * load + math.Clamp(spd * 0.025, 0, 35)
        local baseVol = 0.15 + 0.35 * load
        basePitch = basePitch * (0.85 + 0.15 * battFrac)

        if battFrac < 0.15 then
            basePitch = basePitch + math.sin(CurTime() * 15) * 5
        end

        self.RotorSound:ChangePitch(math.Clamp(basePitch, 55, 180), 0.08)
        self.RotorSound:ChangeVolume(math.Clamp(baseVol, 0.05, 0.55), 0.08)
    end

    if self.WindSound then
        local spd = phys:GetVelocity():Length()
        local windVol = math.Clamp(spd / 800, 0, 0.4)
        local windPitch = 80 + math.Clamp(spd * 0.05, 0, 40)
        self.WindSound:ChangeVolume(windVol, 0.15)
        self.WindSound:ChangePitch(windPitch, 0.15)
    end

    if self:Health() <= 0 then
        local ply2 = self:GetCreator()
        if IsValid(ply2) then
            net.Start("MuR_DroneLost")
            net.Send(ply2)
        end
        self:Explode()
        return true
    end

    local ply2 = self:GetCreator()
    if self:GetNW2Float("RemoveTime") < CurTime() or not IsValid(ply2) or not ply2:Alive() or (ply2.GetSVAnim and ply2:GetSVAnim() ~= "") then
        if IsValid(ply2) then
            net.Start("MuR_DroneLost")
            net.Send(ply2)
            if ply2.ControlDrone == self then
                ply2.ControlDrone = nil
            end
        end
        self:EmitSound("ambient/machines/machine1_hit2.wav", 70, 80, 0.6)
        self:Remove()
    elseif IsValid(ply2) and ply2:KeyDown(IN_RELOAD) and ply2:GetPos():DistToSqr(self:GetPos()) < 50000 then
        ply2:Give("swep_drone")
        ply2:SelectWeapon("swep_drone")
        self:EmitSound("buttons/button14.wav", 60, 100, 0.5)
        if ply2.ControlDrone == self then
            ply2.ControlDrone = nil
        end
        self:Remove()
    end

    self.DeltaTime = CurTime()
    self:NextThink(CurTime())
    return true
end

function ENT:PhysicsCollide(col)
    if self.Velo.x > self.MaxSpeed and self:GetNW2Bool("Boost") then
        self:EmitSound("physics/metal/metal_solid_impact_hard"..math.random(1,5)..".wav", 80, 100, 0.8)
        self:TakeDamage(self:Health())
    end
end

-- ВЗРЫВ С HEAT-ПРОБИТИЕМ, ПОРТНУТ ИЗ КРОКУСА (исправлен для самоуничтожения)
function ENT:Explode()
    if self._Exploding then return end
    self._Exploding = true

    local ply = self:GetCreator()

    if IsValid(ply) then
        net.Start("MuR_DroneLost")
        net.Send(ply)

        if ply.ControlDrone == self then
            ply.ControlDrone = nil
        end
    end

    self:OnFinishExplosion()

    timer.Simple(0, function()
        if IsValid(self) then
            self:Remove()
        end
    end)
end

function ENT:OnFinishExplosion()
    local angle_reg = Angle(0,0,0)
    local angle_dif = Angle(-90,0,0)
    local pos = self:LocalToWorld(self:OBBCenter())

    if self:WaterLevel() >= 1 then
        local tr = util.TraceLine({
            start = pos,
            endpos = pos + Vector(0,0,9000),
            filter  = self,
        })
        local tr2 = util.TraceLine({
            start = tr.HitPos,
            endpos = tr.HitPos - Vector(0,0,9000),
            filter = self,
            mask = MASK_WATER + CONTENTS_TRANSLUCENT,
        })
        if tr2.Hit then
            ParticleEffect(self.EffectWater, tr2.HitPos,(self.AngEffect and angle_dif or angle_reg), nil)
        end
    else
        local tr = util.TraceLine({
            start = pos,
            endpos = pos - Vector(0, 0, self.TraceLength or 150),
            filter = self,
        })
        if tr.HitWorld then
            ParticleEffect(self.Effect, pos, (self.AngEffect and angle_dif or angle_reg), nil)
        else
            ParticleEffect(self.EffectAir, pos, (self.AngEffect and angle_dif or angle_reg), nil)
        end
    end

    if self.HEAT then
        local hitPos = self:GetPos() + self:GetForward() * 20

        local heat = {}
        heat.Src      = hitPos
        heat.Dir      = self:GetForward()
        heat.Spread   = Vector(0,0,0)
        heat.Force    = self.ArmorPenetration + math.Rand(-self.ArmorPenetration * 0.05, self.ArmorPenetration * 0.05)
        heat.HullSize = self.HEATRadius * 2
        heat.Damage   = self.PenetrationDamage + math.Rand(-self.PenetrationDamage * 0.1, self.PenetrationDamage * 0.1)
        heat.Velocity = 30000
        heat.Attacker = self.Owner or self:GetCreator() or self

        if LVS and LVS.FireBullet then
            LVS:FireBullet(heat)
        end

        if self.ExplosionRadius > 0 then
            util.BlastDamage(
                self,
                (IsValid(self:GetCreator()) and self:GetCreator()) or self.Attacker or game.GetWorld(),
                pos,
                self.ExplosionRadius,
                self.ExplosionDamage
            )
            self:BlastDoors(self, pos, 10)
        end

        if self.FragCount > 0 then
            self:Fragmentation(
                self,
                pos,
                10000,
                self.FragDamage,
                self.FragRadius,
                (IsValid(self:GetCreator()) and self:GetCreator()) or self.Attacker or game.GetWorld()
            )
        end
    else
        if self.ExplosionRadius > 0 then
            for _, v in pairs(ents.FindInSphere(pos, self.ExplosionRadius)) do
                if IsValid(v) and not v.SWBombV3 then
                    local dmg = DamageInfo()
                    dmg:SetInflictor(self)
                    dmg:SetDamage(self.ExplosionDamage)
                    dmg:SetDamageType(self.DamageType or DMG_BLAST)
                    dmg:SetAttacker((IsValid(self:GetCreator()) and self:GetCreator()) or self.Attacker or game.GetWorld())
                    v:TakeDamageInfo(dmg)
                end
            end
        end

        if self.BlastRadius > 0 then
            util.BlastDamage(
                self,
                (IsValid(self:GetCreator()) and self:GetCreator()) or self.Attacker or game.GetWorld(),
                pos,
                self.BlastRadius,
                self.ExplosionDamage / 2
            )
            self:BlastDoors(self, pos, 10)
        end

        if self.FragCount > 0 then
            self:Fragmentation(
                self,
                pos,
                10000,
                self.FragDamage,
                self.FragRadius,
                (IsValid(self:GetCreator()) and self:GetCreator()) or self.Attacker or game.GetWorld()
            )
        end
    end

    if swv3 and swv3.CreateSound then
        swv3.CreateSound(pos, false, self.ExplosionSound, self.FarExplosionSound, self.DistExplosionSound)
    else
        sound.Play(self.ExplosionSound or "ambient/explosions/explode_4.wav", pos, 100, 100, 1)
    end
end

function ENT:IsDoor(ent)
    local Class = ent:GetClass()
    return (Class == "prop_door") or (Class == "prop_door_rotating") or (Class == "func_door") or (Class == "func_door_rotating")
end

function ENT:BlastDoors(blaster, pos, power, range, ignoreVisChecks)
    for _, door in pairs(ents.FindInSphere(pos, 40 * power * (range or 1))) do
        if self:IsDoor(door) then
            local proceed = ignoreVisChecks

            if not proceed then
                local tr = util.QuickTrace(pos, door:LocalToWorld(door:OBBCenter()) - pos, blaster)
                proceed = IsValid(tr.Entity) and (tr.Entity == door)
            end

            if proceed then
                self:BlastDoor(door, (door:LocalToWorld(door:OBBCenter()) - pos):GetNormalized() * 1000)
            end
        end

        if door:GetClass() == "func_breakable_surf" then
            door:Fire("Break")
        end
    end
end

function ENT:BlastDoor(ent, vel)
    local Moddel, Pozishun, Ayngul, Muteeriul, Skin = ent:GetModel(), ent:GetPos(), ent:GetAngles(), ent:GetMaterial(), ent:GetSkin()
    sound.Play("Wood_Crate.Break", Pozishun, 60, 100)
    sound.Play("Wood_Furniture.Break", Pozishun, 60, 100)
    ent:Fire("unlock", "", 0)
    ent:Fire("open", "", 0)
    ent:SetNoDraw(true)
    ent:SetNotSolid(true)

    if Moddel and Pozishun and Ayngul then
        local Replacement = ents.Create("prop_physics")
        Replacement:SetModel(Moddel)
        Replacement:SetPos(Pozishun + Vector(0, 0, 1))
        Replacement:SetAngles(Ayngul)

        if Muteeriul then
            Replacement:SetMaterial(Muteeriul)
        end

        if Skin then
            Replacement:SetSkin(Skin)
        end

        Replacement:SetModelScale(.9, 0)
        Replacement:Spawn()
        Replacement:Activate()

        if vel then
            Replacement:GetPhysicsObject():SetVelocity(vel)

            timer.Simple(0, function()
                if IsValid(Replacement) then
                    Replacement:GetPhysicsObject():ApplyForceCenter(vel * 100)
                end
            end)
        end

        timer.Simple(3, function()
            if IsValid(Replacement) then
                Replacement:SetCollisionGroup(COLLISION_GROUP_WEAPON)
            end
        end)

        timer.Simple(30, function()
            if IsValid(ent) then
                ent:SetNotSolid(false)
                ent:SetNoDraw(false)
            end

            if IsValid(Replacement) then
                Replacement:Remove()
            end
        end)
    end
end

function ENT:Fragmentation(shooter, origin, fragNum, fragDmg, fragMaxDist, attacker, direction, spread, zReduction)
    shooter = shooter or game.GetWorld()
    zReduction = zReduction or 2

    local Spred = Vector(0, 0, 0)
    local BulletsFired, MaxBullets, disperseTime = 0, self.FragCount, .5

    if fragNum >= 12000 then
        disperseTime = 2
    elseif fragNum >= 6000 then
        disperseTime = 1
    end

    for i = 1, fragNum do
        timer.Simple((i / fragNum) * disperseTime, function()
            local Dir

            if direction and spread then
                Dir = Vector(direction.x, direction.y, direction.z)
                Dir = Dir + VectorRand() * math.Rand(0, spread)
                Dir:Normalize()
            else
                Dir = VectorRand()
            end

            if zReduction then
                Dir.z = Dir.z / zReduction
                Dir:Normalize()
            end

            local Tr = util.QuickTrace(origin, Dir * fragMaxDist, shooter)

            if Tr.Hit and not Tr.HitSky and not Tr.HitWorld and (BulletsFired < MaxBullets) then
                local LowFrag = (Tr.Entity.IsVehicle and Tr.Entity:IsVehicle()) or Tr.Entity.LFS or Tr.Entity.LVS or Tr.Entity.EZlowFragPlease

                if (not LowFrag) or (LowFrag and math.random(1, 4) == 2) then

                    local firer = (IsValid(shooter) and shooter) or game.GetWorld()

                    firer:FireBullets({
                        Attacker = attacker,
                        Damage = fragDmg,
                        Force = fragDmg / 8,
                        Num = 1,
                        Src = origin,
                        Tracer = 0,
                        Dir = Dir,
                        Spread = Spred,
                        AmmoType = "Buckshot"
                    })
                    BulletsFired = BulletsFired + 1
                end
            end
        end)
    end
end

function ENT:OnTakeDamage(dmgt)
    local dmg = dmgt:GetDamage()
    self:SetHealth(self:Health() - dmg)

    local owner = self:GetCreator()
    if IsValid(owner) then
        owner:ViewPunch(AngleRand(-1, 1))
        local snd = damageSounds[math.random(#damageSounds)]
        self:EmitSound(snd, 75, math.random(90, 110))

        if self:Health() < self.HealthCount * 0.3 and math.random() < 0.3 then
            self:EmitSound("ambient/machines/machine1_hit1.wav", 65, math.random(120, 140), 0.4)
        end
    end
end

hook.Add("SetupPlayerVisibility", "GpincDroneCam", function(ply, viewEntity)
    local drone = ply.ControlDrone
    if IsValid(drone) and drone:GetClass() == "mur_drone_entity" then
        AddOriginToPVS(drone:GetPos())
    end
end)

-- приём команды экстренного самоуничтожения
net.Receive("MuR_DroneEmergency", function(len, ply)
    local drone = ply.ControlDrone

    if not IsValid(drone) or drone:GetClass() ~= "mur_drone_entity" then
        ply.ControlDrone = nil
        return
    end

    if not drone.EmergencyKill then
        drone.EmergencyKill = true
        drone.EmergencyKillTime = CurTime() + 3
        drone:SetNWFloat("EmergencyCountdown", drone.EmergencyKillTime)
        drone:EmitSound("buttons/button17.wav", 75, 100, 0.6)
    end
end)
