--MAXIME
local mysql = exports.mysql
local commandsGM = {{}, {}, {}, {}, {}}
local scriptUpdates = ""

function fetchCommandsGM()
	commandsGM = {{}, {}, {}, {}, {}}
	local count = 0
	local tempCm = {}
	local cmSQL = mysql:query("SELECT * FROM `commands_library` WHERE `cmType`='2' ORDER BY `cmCreationDate` DESC ") or false
	while true do
		local row = mysql:fetch_assoc(cmSQL) or false
		if not row then 
			break 
		end
		table.insert(tempCm, { tonumber(row["cmID"]), tonumber(row["cmLevel"]),row["cmName"],row["cmExplanation"]} )
		count = count + 1
	end
	mysql:free_result(cmSQL)
	
	for key, cmd in pairs(tempCm) do
		if cmd[1] == -2 then
			scriptUpdates = cmd[4]
		else
			table.insert(commandsGM[cmd[2]], {cmd[3], cmd[4], cmd[1]} )
		end
	end
	
	outputDebugString(" Fetched "..count.." GM cmds sucessfully from SQL")
	return count
end


function fetchCmdsManuallyGM(thePlayer, commandName)
	if not exports.integration:isPlayerLeadAdmin(thePlayer) then
		outputChatBox("Only Head Admins and above can access /"..commandName..".", thePlayer, 255,0,0)
		return false
	end
	outputChatBox(" Fetched "..fetchCommandsGM().." GM cmds sucessfully from SQL",thePlayer)
end
addCommandHandler("fetchgh", fetchCmdsManuallyGM)

function showGMCmds(thePlayer, commandName)
	if (exports.integration:isPlayerTrialAdmin(thePlayer) or exports.integration:isPlayerSupporter(thePlayer)) and commandsGM then
		triggerClientEvent(thePlayer, "admin-system:showGMcmds", thePlayer, commandsGM, scriptUpdates)
	end
end
addCommandHandler("gh", showGMCmds)

function initiateShitGM ()
	fetchCommandsGM()
	setTimer(fetchCommandsGM, 60000*60*3, 0) -- Every 3 hours
end
addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), initiateShitGM)

function delCmdGM(thePlayer, cmdID, cmdName)
	if mysql:query("DELETE FROM `commands_library` WHERE `cmID`='"..tostring(cmdID).."' AND `cmType`='2' ") then
		local adminUsername = getElementData(thePlayer, "account:username")
		local adminTitle = exports.global:getPlayerAdminTitle(thePlayer)
		exports.global:sendMessageToSupporters("[CMD LIBRARY]: ".. adminTitle.. " "..adminUsername.." has deleted GM command /"..cmdName.." from /gh.",true)
		exports.global:sendMessageToAdmins("[CMD LIBRARY]: ".. adminTitle.. " "..adminUsername.." has deleted GM command /"..cmdName.." from /gh.", true)
		fetchCommandsGM()
		triggerClientEvent(thePlayer, "admin-system:showGMcmds", thePlayer, commandsGM, scriptUpdates)
	else
		outputChatBox("Failed to delete cmd /"..cmdName..". DB Error.", thePlayer, 255,0,0)
	end
end
addEvent("admin-system:delCmdGM", true)
addEventHandler("admin-system:delCmdGM", getRootElement(), delCmdGM)

function saveCmdGM(thePlayer, cmdID, cmdName, cmdEx, cmdAccess, cmdType)
	if cmdID then
		if mysql:query("UPDATE `commands_library` SET `cmType`='"..cmdType.."', `cmLevel`='"..cmdAccess.."', `cmName`='"..tostring(cmdName):gsub("'","''").."', `cmExplanation`='"..tostring(cmdEx):gsub("'","''").."' WHERE `cmID`='"..cmdID.."' ") then
			local adminUsername = getElementData(thePlayer, "account:username")
			local adminTitle = exports.global:getPlayerAdminTitle(thePlayer)
			exports.global:sendMessageToSupporters("[CMD LIBRARY]: "..adminTitle.." "..adminUsername.." has modified GM command /"..cmdName.." ("..cmdEx..")", true)
			exports.global:sendMessageToAdmins("[CMD LIBRARY]: "..adminTitle.." "..adminUsername.." has modified GM command /"..cmdName.." ("..cmdEx..")", true)
			fetchCommandsGM()
			triggerClientEvent(thePlayer, "admin-system:showGMcmds", thePlayer, commandsGM, scriptUpdates)
		else
			outputChatBox("Failed to modify cmd /"..cmdName..". DB Error.", thePlayer, 255,0,0)
		end
	else
		if mysql:query("INSERT INTO `commands_library` SET `cmType`='"..cmdType.."', `cmLevel`='"..cmdAccess.."', `cmName`='"..tostring(cmdName):gsub("'","''").."', `cmExplanation`='"..tostring(cmdEx):gsub("'","''").."' ") then
			local adminUsername = getElementData(thePlayer, "account:username")
			local adminTitle = exports.global:getPlayerAdminTitle(thePlayer)
			exports.global:sendMessageToSupporters("[CMD LIBRARY]: "..adminTitle.." "..adminUsername.." has added GM command /"..cmdName.." ("..cmdEx..")", true)
			exports.global:sendMessageToAdmins("[CMD LIBRARY]: "..adminTitle.." "..adminUsername.." has added GM command /"..cmdName.." ("..cmdEx..")", true)
			fetchCommandsGM()
			triggerClientEvent(thePlayer, "admin-system:showGMcmds", thePlayer, commandsGM, scriptUpdates)
		else
			outputChatBox("Failed to add cmd /"..cmdName..". DB Error.", thePlayer, 255,0,0)
		end
	end
end
addEvent("admin-system:saveCmdGM", true)
addEventHandler("admin-system:saveCmdGM", getRootElement(), saveCmdGM)

function updateScriptSQLGM(thePlayer, content)
	if mysql:query("UPDATE `commands_library` SET `cmExplanation`='"..tostring(content):gsub("'","''").."' WHERE `cmID`='-2' AND `cmType`='2'") then
		fetchCommandsGM()
		triggerClientEvent(thePlayer, "admin-system:showGMcmds", thePlayer, commandsGM, scriptUpdates)
	else
		outputChatBox("Failed to update script changes. DB Error.", thePlayer, 255,0,0)
	end
end
addEvent("admin-system:updateScriptGM", true)
addEventHandler("admin-system:updateScriptGM", getRootElement(), updateScriptSQLGM)