local playerIntentionallyTurnedOff = false

RegisterCommand("toggleengine", function()
    local ped = PlayerPedId()
    if IsPedInAnyVehicle(ped, false) then
        local veh = GetVehiclePedIsIn(ped, false)
        if GetPedInVehicleSeat(veh, -1) == ped then
            local isRunning = GetIsVehicleEngineRunning(veh)

            -- Toggle engine state
            SetVehicleEngineOn(veh, not isRunning, true, false)

            -- Update protection flag
            playerIntentionallyTurnedOff = isRunning
        end
    end
end, false)

RegisterKeyMapping("toggleengine", "Toggle Engine On/Off", "keyboard", "H")

Citizen.CreateThread(function()
    while true do
        Wait(0) -- every frame

        local ped = PlayerPedId()
        if IsPedInAnyVehicle(ped, false) then
            local veh = GetVehiclePedIsIn(ped, false)

            -- Only if player is pilot
            if GetPedInVehicleSeat(veh, -1) == ped then
                local vehClass = GetVehicleClass(veh)
                local isPlane = vehClass == 16 -- 16 = Planes

                if isPlane then
                    local isRunning = GetIsVehicleEngineRunning(veh)

                    -- If engine is off but player didn't toggle it off manually
                    if not isRunning and not playerIntentionallyTurnedOff then
                        -- Force it back on immediately
                        SetVehicleEngineOn(veh, true, true, false)
                    elseif isRunning and playerIntentionallyTurnedOff then
                        -- Engine is running again, reset flag
                        playerIntentionallyTurnedOff = false
                    end
                end
            end
        end
    end
end)
