--// SProtect by Itzt: V1.0


local M = require(script.Settings)
local RS = game:GetService("RunService")

local locked = true

function count()
	local z = 0
	if M.onlyme then
		local v = M.owners[1]
		if game.Players:FindFirstChild(v) then
			z += 1
		else
			if tonumber(v) ~= nil then
				if game.Players:GetPlayerByUserId(v) then
					z += 1
				end
			end
		end
	else
		for i,v in pairs(M.owners) do
			if game.Players:FindFirstChild(v) then
				z += 1
			else
				if tonumber(v) ~= nil then
					if game.Players:GetPlayerByUserId(v) then
						z += 1
					end
				end
			end
		end
	end
	return z
end

function search(t,p)
	local x = string.lower(p.Name)
	if table.find(t,x) or table.find(t,p.UserId) then
		return true
	else
		return false
	end
end

game.Players.PlayerAdded:connect(function(x)
	if search(M.owners,x) then
		--print("Owner of car granted permissions")
		x.Chatted:connect(function(z)
			if string.lower(z) == string.lower(M.delmsg) then
				script.Parent:Destroy()
			elseif string.lower(z) == string.lower(M.carname.." "..M.unlock) then
				locked = false
			elseif string.lower(z) == string.lower(M.carname.." "..M.lock) then
				locked = true
			end
		end)
	end
end)

wait(2)

for i,x in pairs(game.Players:GetChildren()) do
	if search(M.owners,x) then
		--print("Owner of car granted permissions")
		x.Chatted:connect(function(z)
			if string.lower(z) == string.lower(M.delmsg) then
				script.Parent:Destroy()
			elseif string.lower(z) == string.lower(M.carname.." "..M.unlock) then
				locked = false
			elseif string.lower(z) == string.lower(M.carname.." "..M.lock) then
				locked = true
			end
		end)
	end
end

if (RS:IsStudio() and M.studioperms) then
	warn("studio detected, car will not lock")
elseif count() == 0 then
	warn("no owners found, deleting")
	script.Parent:Destroy()
	script:Destroy()
end

game.Players.PlayerRemoving:connect(function(x)
	if count() == 0 then
		script.Parent:Destroy()
	end
end)

script.Parent.DriveSeat.ChildAdded:connect(function(child)
	if child.Name == "SeatWeld" then
		if child.Part1.Name == "HumanoidRootPart" then
			local x = game.Players:GetPlayerFromCharacter(child.Part1.Parent)
			if search(M.owners,x) or (RS:IsStudio() and M.studioperms) or (locked==false) then
			else
				wait() --prevent the car from becoming unusable
				child:Destroy()
				if M.lethal then
				x.Character.Humanoid.Health -= x.Character.Humanoid.Health
				else
					x:LoadCharacter()
				end
			end
		end
	end
end)
