-- server.lua

local currentVersion = "v4.0"
local githubRawURL = "https://raw.githubusercontent.com/SantosMods/SandyMotelConstruction/refs/heads/main/version"

local latestVersion = "unknown"
local releaseStage = "unknown"
local changelog = "N/A"
local website = "https://santosmods.dev"
local feedback = "https://santosmods.dev"
local resourceName = GetCurrentResourceName()

-- ANSI color codes
local colors = {
    reset  = "\27[0m",
    white  = "\27[97m",
    green  = "\27[92m",
    yellow = "\27[93m",
    red    = "\27[91m",
    cyan   = "\27[96m",
    gray   = "\27[90m",
    blue   = "\27[94m"
}

-- Center text
local function centerText(text, width)
    width = width or 100
    local pad = math.floor((width - #text) / 2)
    return string.rep(" ", pad) .. text
end

-- Print the banner
local function logBanner()
    print("\n\n")
    print(colors.blue   .. centerText("SandyMotelConstruction"))
    print(colors.white  .. centerText("Thank you for using SantosMods.dev") .. "\n")

    print(colors.yellow .. centerText("Release Stage: " .. releaseStage))
    print(colors.gray   .. centerText("Resource: " .. resourceName) .. "\n")

    print(colors.green  .. centerText("Using Version: " .. currentVersion))
    print(colors.red    .. centerText("Latest Version: " .. latestVersion) .. "\n")

    print(colors.white  .. centerText("CHANGELOG"))
    print(colors.white  .. centerText("• " .. changelog) .. "\n")

    print(colors.cyan   .. centerText("Website: " .. website))
    print(colors.gray   .. centerText("Support: " .. feedback) .. "\n")

    print(colors.white  .. centerText("© 2025 SantosMods.dev - All Rights Reserved"))
    print(colors.reset)
    print("\n\n")
end

-- Fetch version info
local function fetchVersionInfo()
    PerformHttpRequest(githubRawURL, function(code, body)
        if code == 200 and body then
            for line in string.gmatch(body, "[^\r\n]+") do
                local key, value = line:match("^(.-)=(.-)$")
                if key == "latest_version" then latestVersion = value end
                if key == "release_stage"   then releaseStage = value end
                if key == "changelog"       then changelog = value end
            end
        else
            print(colors.red .. "[SandyMotelConstruction] Failed to fetch version info. HTTP " .. tostring(code) .. colors.reset)
        end

        logBanner()
    end, "GET", "", { ["Content-Type"] = "text/plain" })
end

-- Resource start
AddEventHandler("onResourceStart", function(resource)
    if resource ~= resourceName then return end
    Citizen.Wait(300)
    fetchVersionInfo()
end)
