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

util.AddNetworkString("MedicTerminalNPC_Menu")
util.AddNetworkString("MedicTerminalNPC_Buy")

function ENT:Initialize()
	self:SetModel("models/Humans/Group03m/Female_01.mdl")
	self:PhysicsInit(SOLID_BBOX)
	self:SetSolid(SOLID_BBOX)
	self:SetMoveType(MOVETYPE_STEP)
	self:SetCollisionBounds(Vector(-16, -16, 0), Vector(16, 16, 72))
	self:SetUseType(SIMPLE_USE)
	self:DropToFloor()
	
	local phys = self:GetPhysicsObject()
	if IsValid(phys) then
		phys:Wake()
		phys:EnableMotion(false)
	end

	-- Анимация простоя (как у ix_shop_npc)
	local sequence = self:LookupSequence("idle_subtle")
	if sequence > 0 then
		self:ResetSequence(sequence)
	end
end

function ENT:Think()
	self:NextThink(CurTime())
	return true
end

function ENT:Use(activator, caller)
	if not IsValid(activator) or not activator:IsPlayer() then return end
	
	net.Start("MedicTerminalNPC_Menu")
		net.WriteEntity(self)
	net.Send(activator)
end

net.Receive("MedicTerminalNPC_Buy", function(len, ply)
	local npc = net.ReadEntity()
	local itemClass = net.ReadString()
	
	if not IsValid(npc) or ply:GetPos():DistToSqr(npc:GetPos()) > 60000 then return end
	
	if not ix then return end -- Using Helix
	local char = ply:GetCharacter()
	if not char then return end

	local items = npc:GetShopItems()
	local itemInfo = items[itemClass]
	
	if not itemInfo then return end
	
	local price = itemInfo.price
	local name = itemInfo.name
	local isWeapon = itemInfo.isWeapon
	
	if price <= 0 then return end
	
	if not char:HasMoney(price) then
		ply:Notify("У вас недостаточно средств!")
		return
	end
	
	if isWeapon then
		if ply:HasWeapon(itemClass) then
			ply:Notify("У вас уже есть " .. name .. "!")
			return
		end
		
		char:TakeMoney(price)
		ply:Give(itemClass)
		
		-- Custom behavior for first aid kit as defined in MedicMod
		timer.Simple(0.1, function()
			if not IsValid(ply) then return end
			local weap = ply:GetWeapon(itemClass)
			if IsValid(weap) and itemClass == "first_aid_kit" then
				if weap.SetBandage then weap:SetBandage(3) end
				if weap.SetAntidote then weap:SetAntidote(1) end
				if weap.SetMorphine then weap:SetMorphine(2) end
			end
		end)
		
		ply:Notify("Вы купили " .. name .. " за " .. ix.currency.Get(price))
		
	else
		-- It's an entity
		char:TakeMoney(price)
		
		local ent = ents.Create(itemClass)
		if IsValid(ent) then
			local spawnPos = npc:GetPos() + npc:GetForward() * 50 + Vector(0, 0, 10)
			ent:SetPos(spawnPos)
			ent:SetAngles(npc:GetAngles())
			ent:Spawn()
			ent:Activate()
			
			if CPPI then ent:CPPISetOwner(ply) end
			
			ply:Notify("Вы купили " .. name .. " за " .. ix.currency.Get(price) .. ". Предмет появился рядом с продавцом.")
		end
	end
end)
